Android Volley Use JSONArray as request body

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The default requests integrated in volley don't allow to pass a JSONArray as request body in a POST request. Instead, you can only pass a JSON object as a parameter.

However, instead of passing a JSON object as a parameter to the request constructor, you need to override the getBody() method of the Request.class. You should pass null as third parameter as well:

JSONArray requestBody = new JSONArray();

new JsonObjectRequest(Request.Method.POST, REQUEST_URL, null, RESP_LISTENER, ERR_LISTENER) {
    @Override
    public byte[] getBody() {
        try {
            return requestBody.toString().getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            // error handling
            return null;
        }
    }
};

Explanation of the parameters:

  • REQUEST_URL - The full URL to send your request to.
  • RESP_LISTENER - A Response.Listener<?> object, whose onResponse(T data) method is called upon successful completion.
  • ERR_LISTENER - A Response.ErrorListener object, whose onErrorResponse(VolleyError e) method is called upon an unsuccessful request.


Got any Android Question?