Volley JsonObjectRequest Post request not working

后端 未结 9 1867
有刺的猬
有刺的猬 2020-11-22 06:25

I am using android Volley for making a request. So I use this code. I don\'t understand one thing. I check in my server that params is always null. I consider that getParams

9条回答
  •  旧时难觅i
    2020-11-22 07:08

    try to use this helper class

    import java.io.UnsupportedEncodingException;
    import java.util.Map;    
    import org.json.JSONException;
    import org.json.JSONObject;    
    import com.android.volley.NetworkResponse;
    import com.android.volley.ParseError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.Response.ErrorListener;
    import com.android.volley.Response.Listener;
    import com.android.volley.toolbox.HttpHeaderParser;
    
    public class CustomRequest extends Request {
    
        private Listener listener;
        private Map params;
    
        public CustomRequest(String url, Map params,
                Listener reponseListener, ErrorListener errorListener) {
            super(Method.GET, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
        }
    
        public CustomRequest(int method, String url, Map params,
                Listener reponseListener, ErrorListener errorListener) {
            super(method, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
        }
    
        protected Map getParams()
                throws com.android.volley.AuthFailureError {
            return params;
        };
    
        @Override
        protected Response parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new JSONObject(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    
        @Override
        protected void deliverResponse(JSONObject response) {
            // TODO Auto-generated method stub
            listener.onResponse(response);
        }
    }
    

    In activity/fragment do use this

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());
    
    requestQueue.add(jsObjRequest);
    

提交回复
热议问题