Android中使用Volley传递JSON请求体的实现方法指引
Hey there! Let's tackle your Volley request issues step by step.
Why Your StringRequest with getParams() Isn't Working
First off, the getParams() method in StringRequest is built for sending form-data (x-www-form-urlencoded) parameters, but what you need is a raw JSON request body. That's why your attempts with getParams() keep failing—we need to tweak the request to send JSON instead of form data.
Fixing the StringRequest to Send JSON Body
Here's how to modify your reqrej method to send the JSON body {"data":[{"id":"12"}]}:
// Define your target URL and JSON request body string private static final String REQUEST_URL = "your_api_endpoint_here"; String jsonRequestBody = "{\"data\":[{\"id\":\"12\"}]}"; public void reqrej() { StringRequest stringRequest = new StringRequest(Request.Method.POST, REQUEST_URL, response -> { // Handle successful response Log.d("VolleySuccess", "Response: " + response); }, error -> { // Handle error Log.e("VolleyError", "Request failed: " + error.getMessage()); }) { @Override public byte[] getBody() throws AuthFailureError { // Convert your JSON string to a byte array for the request body try { return jsonRequestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return super.getBody(); } } @Override public Map<String, String> getHeaders() throws AuthFailureError { // Set the correct Content-Type header so the server recognizes JSON Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=utf-8"); return headers; } }; // Add the request to your Volley queue Volley.newRequestQueue(getApplicationContext()).add(stringRequest); }
Key changes here:
- We override
getBody()to return the JSON string as a UTF-8 byte array - We set the
Content-Typeheader toapplication/jsoningetHeaders()so the server knows how to parse the request
Using JsonObjectRequest for JSON Requests
If you prefer a more native approach for JSON payloads, JsonObjectRequest is designed exactly for this. It handles JSON serialization and deserialization out of the box:
public void sendJsonRequest() { try { // Build your JSON request body programmatically JSONObject requestBody = new JSONObject(); JSONArray dataArray = new JSONArray(); JSONObject item = new JSONObject(); item.put("id", "12"); dataArray.put(item); requestBody.put("data", dataArray); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, REQUEST_URL, requestBody, // Pass the JSONObject directly as the request body response -> { // Handle successful JSON response Log.d("VolleyJsonSuccess", "Response: " + response.toString()); }, error -> { // Handle error Log.e("VolleyJsonError", "Request failed: " + error.getMessage()); }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { // Explicitly set Content-Type (some servers require this, even though JsonObjectRequest defaults to it) Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=utf-8"); return headers; } }; // Add to Volley queue Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest); } catch (JSONException e) { e.printStackTrace(); // Handle JSON parsing errors here } }
This approach avoids manually writing JSON strings, reducing the chance of syntax errors. Just build your JSONObject and JSONArray programmatically, then pass the root JSONObject to the JsonObjectRequest constructor.
内容的提问来源于stack exchange,提问作者android developer

