【问题标题】:Android Volley BasicNetwork.performRequest: Unexpected response code 400 for URLAndroid Volley BasicNetwork.performRequest:URL 的意外响应代码 400
【发布时间】:2018-02-07 12:57:51
【问题描述】:

我在 android 中使用 Volley 调用网络服务。我在日志中有以下错误

D/libc-netbsd: [getaddrinfo]: hostname=192.168.66.86; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
D/libc-netbsd: [getaddrinfo]: hostname=192.168.66.86; servname=(null); cache_mode=(null), netid=0; mark=0
D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
I/System.out: [CDS]rx timeout:2500
I/System.out: [socket][2] connection /123.231.66.86:8080;LocalPort=56586(2500)
I/System.out: [CDS]connect[/192.168.66.86:8080] tm:2
I/System.out: [socket][/192.168.8.104:56586] connected
I/System.out: [OkHttp] sendRequest>>
I/System.out: OkBuffer write source.head == null !
I/System.out: [OkHttp] sendRequest<<
I/System.out: Close in OkHttp:0
I/System.out: [CDS]close[56586]
E/Volley: [2259] BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.66.86:8080/jlrloyalty/rest/usr/login
D/Volley: [1] 2.onErrorResponse: JsonRequestActivity

我的代码是这样的

private void makeJsonObjReq() {
        showProgressDialog();
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
                Const.URL_STRING_REQ, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        msgResponse.setText(response.toString());
                        hideProgressDialog();
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {

            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                return headers;
            }

            @Override
            public byte[] getBody() {
                return super.getBody();
            }

            @Override
            protected Map<String, String> getParams() {
                Gson gson = new Gson();
                LoginAccount loginAccount = new LoginAccount();

                HTTPWebServiceRequest httpWebServiceRequest = new HTTPWebServiceRequest();
                loginAccount.setUsername("neshan");
                loginAccount.setPassword("123456");
                httpWebServiceRequest.setRequestObject(loginAccount);
                String jsonParam = gson.toJson(loginAccount);

                Map<String, String> params = new HashMap<String, String>();
                params.put("requestObject", jsonParam);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq,
                tag_json_obj);

但是当我使用以下参数从 Postman 调用此 url 时,它可以工作。

{"requestObject":{"password":"123456","username":"neshan","loginId":0}}

当我调试代码时,两个请求参数都是相同的。内容类型为application/json。但是这里发生了什么?有什么线索吗?

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    在 volley 中,您有单独的成功和错误侦听器,处理错误侦听器块中的所有错误。

    显示一个警报,您可以在其中向用户显示适当的消息,以便通知他有错误,他需要重试。

    否则,如果您出于特定原因使用自定义错误代码,则可以通过创建自己的错误侦听器来全局处理该错误侦听器,该侦听器实现了 volley 的 Response.ErrorListener。

    谷歌“volley error handling generalized”你会得到一些参考。

    【讨论】:

    • 谢谢。但我想知道我在这里做错了什么,因为 volley 和 postman 的相同请求会给出两种不同的结果。
    【解决方案2】:

    重写getBody方法如下:

    public byte[] getBody() throws AuthFailureError {
      Map<String, String> params = getParams();
      if (params != null && params.size() > 0) {
         if (getBodyContentType().equals("application/json")) {
           return params.get("json").getBytes(getParamsEncoding());
         }
      else
            return encodeParameters(params, getParamsEncoding());
      }
              return null;
        }
    byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
                    StringBuilder encodedParams = new StringBuilder();
                    try {
                        if (getBodyContentType().equals("application/json")) {
                                JSONObject obj=new JSONObject(params);
                                obj.toString().getBytes(paramsEncoding);
    
                        } else {
                            for (Map.Entry<String, String> entry : params.entrySet()) {
                                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                                encodedParams.append('=');
                                encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                                encodedParams.append('&');
                            }
                            return encodedParams.toString().getBytes(paramsEncoding);
                        }
                    } catch (UnsupportedEncodingException uee) {
                        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多