Volley JSONArrayRequest with JSONObject as parameter

前端 未结 3 2081
遇见更好的自我
遇见更好的自我 2020-12-10 00:16

I need to make a request with a JSONObject as follows:

{
    \'LangIDs\': [1, 2],
    \'GenreIDs\': [4],
    \'LowPrice\': 0,
    \'HighPrice\': 999,
    \'S         


        
3条回答
  •  萌比男神i
    2020-12-10 00:36

    I created a custom volley request that accepts a JSONObject as parameter.

    CustomJsonArrayRequest.java

     public class CustomJsonArrayRequest extends 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 CustomJsonArrayRequest(int method, String url, JSONObject jsonRequest,
                                    Listener listener, ErrorListener errorListener) {
                super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                        errorListener);
            }
    
            @Override
            protected Response parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                    return Response.success(new JSONArray(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }
        }
    

    How to use?

    JSONObject body = new JSONObject();
    // Your code, e.g. body.put(key, value);
    CustomJsonArrayRequest req = new CustomJsonArrayRequest(Request.Method.POST, url, body, success, error);
    

提交回复
热议问题