首页 文章

Volley JsonObjectRequest发布请求无效

提问于
浏览
72

我正在使用android Volley提出请求 . 所以我使用这段代码 . 我不明白一件事 . 我检查我的服务器,params始终为null . 我认为getParams()不起作用 . 我该怎么做才能解决这个问题 .

RequestQueue queue = MyVolley.getRequestQueue();
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println(response);
                        hideProgressDialog();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                      hideProgressDialog();
                    }
                }) {
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("id","1");
                params.put("name", "myname");
                return params;
            };
        };
        queue.add(jsObjRequest);

7 回答

  • 1

    尝试使用这个助手类

    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<JSONObject> {
    
        private Listener<JSONObject> listener;
        private Map<String, String> params;
    
        public CustomRequest(String url, Map<String, String> params,
                Listener<JSONObject> reponseListener, ErrorListener errorListener) {
            super(Method.GET, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
        }
    
        public CustomRequest(int method, String url, Map<String, String> params,
                Listener<JSONObject> reponseListener, ErrorListener errorListener) {
            super(method, url, errorListener);
            this.listener = reponseListener;
            this.params = params;
        }
    
        protected Map<String, String> getParams()
                throws com.android.volley.AuthFailureError {
            return params;
        };
    
        @Override
        protected Response<JSONObject> 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);
        }
    }
    

    在activity / fragment中使用它

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

    您可以创建自定义 JSONObjectReuqest 并覆盖 getParams 方法,或者您可以在构造函数中将它们作为 JSONObject 提供到请求的正文中 .

    像这样(我编辑了你的代码):

    JSONObject obj = new JSONObject();
    obj.put("id", "1");
    obj.put("name", "myname");
    
    RequestQueue queue = MyVolley.getRequestQueue();
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,obj,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                 System.out.println(response);
                 hideProgressDialog();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 hideProgressDialog();
            }
        });
    queue.add(jsObjRequest);
    
  • 27

    对我来说很容易!几个星期前我得到了它:

    这是 getBody() 方法,而不是 getParams() 中的帖子请求 .

    这是我的:

    @Override
    /**
     * Returns the raw POST or PUT body to be sent.
     *
     * @throws AuthFailureError in the event of auth failure
     */
    public byte[] getBody() throws AuthFailureError {
        //        Map<String, String> params = getParams();
        Map<String, String> params = new HashMap<String, String>();
        params.put("id","1");
        params.put("name", "myname");
        if (params != null && params.size() > 0) {
            return encodeParameters(params, getParamsEncoding());
        }
        return null;
    
    }
    

    (我假设你要发布你在getParams中写的params)

    我给构造函数中的请求提供了参数,但由于您正在动态创建请求,因此您可以在覆盖getBody()方法的内部对其进行硬编码 .

    这就是我的代码:

    Bundle param = new Bundle();
        param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
        param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
        param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);
    
        switch (type) {
        case RequestType.POST:
            param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
            SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));
    

    如果你想要更多这个最后的字符串参数来自:

    param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();
    

    paramasJObj是这样的: {"id"="1","name"="myname"} 通常的JSON字符串 .

  • 1

    当您使用JsonObject请求时,您需要在初始化中传递链接后立即传递参数,请查看以下代码:

    HashMap<String, String> params = new HashMap<>();
            params.put("user", "something" );
            params.put("some_params", "something" );
    
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
    
               // Some code 
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //handle errors
            }
        });
    
    
    }
    
  • 126

    您需要做的就是覆盖Request类中的getParams方法 . 我有同样的问题,我搜索了答案,但我找不到合适的答案 . 问题与get请求不同,服务器重定向的post参数可能会被丢弃 . 例如,阅读this . 因此,请不要冒着Web服务器重定向您的请求的风险 . 如果您要定位http://example/myapp,请提及您服务的确切地址,即http://example.com/myapp/index.php .
    排球很好并且运作完美,问题源于其他地方 .

  • 2

    覆盖函数getParams工作正常 . 您使用POST方法,并将jBody设置为null . 这就是为什么它不起作用 . 如果要发送null jBody,可以使用GET方法 . 我已经覆盖了方法getParams,它可以使用POST方法(和jBody!= null)使用GET方法(和null jBody)

    还有所有的例子here

  • 1

    我有一次相同的问题,空的POST数组是由于请求的重定向(在服务器端)引起的,修复了URL,因此当它到达服务器时不必重定向 . 例如,如果使用服务器端应用程序上的.htaccess文件强制使用https,请确保您的客户端请求具有“https://”前缀 . 通常在重定向发生时,POST数组会丢失 . 我希望这有帮助!

相关问题