Android Volley Post Request - Workaround for JsonArrayRequest

后端 未结 1 1869
谎友^
谎友^ 2021-01-15 03:59

I understand that POST requests using JsonArrayRequest are not available out of the box with Volley, but I saw this post here that talked about adding a constructor to handl

相关标签:
1条回答
  • 2021-01-15 04:50

    Create a class and extend JsonArrayRequest then override

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("name", "value");
        return params;
    }
    

    and add a new constructor and in it call

    super(Method.POST, url, null, listener, errorListener);
    

    or use this class

    public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
    
        /**
         * Creates a new request.
         * @param url URL to fetch the JSON from
         * @param listener Listener to receive the JSON response
         * @param errorListener Error listener, or null to ignore errors.
         */
        public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
            super(Method.POST, url, null, listener, errorListener);
        }
    
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("name", "value");
            return params;
        }
    
        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString =
                        new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                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));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题