anthony anthony - 4 months ago 29
Android Question

Send POST request with JSON data using Volley

I would like to send a new

JsonObjectRequest
request:


  • I want to receive JSON data (response from server): OK

  • I want to send JSON formatted data with this request to the server

    JsonObjectRequest request = new JsonObjectRequest(
    Request.Method.POST, "myurl.com", null,
    new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
    //...
    }
    },
    new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    //...
    }
    })
    {
    @Override
    protected Map<String,String> getParams() {
    // something to do here ??
    return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
    // something to do here ??
    return params;
    }
    };



P.S. I use GSON library in my project too.

Answer

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}