Send a JSONArray POST request with android volley library

后端 未结 4 733
醉梦人生
醉梦人生 2020-12-11 10:19

I would like to send and receive a Json Array with volley. Now I can receive an array and it\'s ok but I don\'t know how to send a request (For example: with post method).<

4条回答
  •  遥遥无期
    2020-12-11 10:53

    Create a class and extend JsonArrayRequest then override

    @Override
    protected Map getParams() throws AuthFailureError {
        HashMap params = new HashMap();
        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 {
    
        /**
         * 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 listener, Response.ErrorListener errorListener) {
            super(Method.POST, url, null, listener, errorListener);
        }
    
        @Override
        protected Map getParams() throws AuthFailureError {
            HashMap params = new HashMap();
            params.put("name", "value");
            return params;
        }
    
        @Override
        protected Response 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));
            }
        }
    }
    

提交回复
热议问题