Send POST request with JSON data using Volley

前端 未结 8 626
梦谈多话
梦谈多话 2020-11-22 12:07

I would like to send a new JsonObjectRequest request:

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

8条回答
  •  遇见更好的自我
    2020-11-22 12:51

    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() { ... });
    

    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 listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                    errorListener);
    }
    

提交回复
热议问题