Android Volley BasicNetwork.performRequest: Unexpected response code 400 for URL

谁说我不能喝 提交于 2019-12-24 19:14:31

问题


I call a webservice using Volley in android. I have the following error in the log

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

My code is like this

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);

But when I call this url from Postman with following parameters it works.

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

when I debug the code both the request params are same. The content type is application/json. But what going on here? Any clue?


回答1:


In volley you have separate success and error listeners, handle all the errors in the error listener block.

Display a alert or so in which you can show a proper message for user, so that he gets notified that there was an error and he needs to try again.

Or else if you are using custom error code for specific reason you can handle that globally by creating your own error listeners which implements volley's Response.ErrorListener.

Google “volley error handling generalized” you will get some references.




回答2:


Override getBody method as below:

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);
                }
            }


来源:https://stackoverflow.com/questions/48664436/android-volley-basicnetwork-performrequest-unexpected-response-code-400-for-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!