Android Volley gives me 400 error

后端 未结 12 2126
借酒劲吻你
借酒劲吻你 2020-12-11 00:28

I\'m trying to make a POST request to my API and it works in Postman (I get a valid JSON object), but not using Volley. With the follo

相关标签:
12条回答
  • 2020-12-11 00:57

    If you are passing the json value to in body(raw json).No need to set the content type as headers.put("Content-Type", "application/json; charset=utf-8");

    When I was using the content type in header callback ,the 400 response status I was getting in logcat.I commented headers.put("Content-Type", "application/json; charset=utf-8"); as because I am passing raw json in body while calling api.screenshot for postman is attached.It will help

    private void volleyCall(String email, String password) {
    
          RequestQueue queue= Volley.newRequestQueue(this);
          String URL = "http://XXXX.in:8080/XXXX/api/userService/login";
    
          Map<String, String> jsonParams = new HashMap<String, String>();
          jsonParams.put("email", email);
          jsonParams.put("password", password);
          Log.d(TAG,"Json:"+ new JSONObject(jsonParams));
    
          JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, URL,new JSONObject(jsonParams),
                  new Response.Listener<JSONObject>() {
                      @Override
                      public void onResponse(JSONObject response) {
                          Log.d(TAG,"Json"+ response);
                      }
                  },
                  new Response.ErrorListener() {
                      @Override
                      public void onErrorResponse(VolleyError error) {
                          //   Handle Error
                          Log.d(TAG, "Error: " + error
                                  + "\nStatus Code " + error.networkResponse.statusCode
                                  + "\nResponse Data " + error.networkResponse.data
                                  + "\nCause " + error.getCause()
                                  + "\nmessage" + error.getMessage());
                      }
                  }) {
              @Override
              public Map<String, String> getHeaders() throws AuthFailureError {
                  HashMap<String, String> headers = new HashMap<String,String>();
                 // headers.put("Content-Type", "application/json; charset=utf-8");
                  return headers;
              }
              @Override
              public String getBodyContentType() {
                  return "application/json";
              }
    
    
    
          };
    
          queue.add(postRequest);
    
      }
    

    LogCat:
    LoginActivity: Json:{"email":"XXXXXX@gmail.com","password":"abcde"}
    LoginActivity: Error: com.android.volley.ServerError
                                                                              
    Status Code 400                                                                     
    Response Data [B@63ca992                                                                              
    Cause null                                                                              
    messagenull
    

    0 讨论(0)
  • 2020-12-11 00:59

    400 error is because Content-Type is set wrong. Please do the following.

    1. GetHeader function should be as

          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
      
              Map<String, String> param = new HashMap<String, String>();
      
              return param;
          }
      
    2. Add this new override function.

          @Override
          public String getBodyContentType() {
              return "application/json";
          }
      
    0 讨论(0)
  • 2020-12-11 01:01

    Check if you are using correct SDK

    For Android Studio / IntelliJIDEA:

    File -> Project Structure -> Project -> Project SDK 
    Modules -> Check each modules "Module SDK" 
    

    Preferably, you should use "Google API (x.x)" instead of Android API

    0 讨论(0)
  • 2020-12-11 01:11

    I had the same problem and i removed from the header:

      headers.put("Content-Type", "application/json");
    

    now it works great!

    0 讨论(0)
  • 2020-12-11 01:11

    There can be multiple reasons for this error.

    One reason, of course, as said by others, is that maybe you are missing or have improperly set 'Content-type' header.

    If you have properly implemented that, another possible reason is that you are sending params directly from your URL. There may be a case when params is a string with some white spaces in it. These white spaces cause problems in GET requests through Volley. You need to find another way around it. That's all.

    0 讨论(0)
  • 2020-12-11 01:12

    I have the same issue before and I got the solution in my project:

    RequestQueue requestManager = Volley.newRequestQueue(this);
    
            String requestURL = "http://www.mywebsite.org";
            Listener<String> jsonListerner = new Response.Listener<String>() {
                @Override
                public void onResponse(String list) {
    
                }
            };
    
            ErrorListener errorListener = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.w("Volley Error", error.getMessage());
                }
            };
    
            StringRequest fileRequest = new StringRequest(Request.Method.POST, requestURL, jsonListerner,errorListener){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("token", account.getToken());
                    return params;
                }
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    // do not add anything here
                    return headers;
                }
            };
            requestManager.add(fileRequest);
    

    In the code Snippet above I used Post Method:

    My answer is base on my experience and so take note:

    1.) When using POST method use "StringRequest" instead of "JsonObjectRequest"

    2.) inside getHeaders Override the value with an Empty HashMap

     example snippet:
    
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<String, String>();
                params.put("token", account.getToken());
                return params;
            }
    
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                // do not add anything here
                return headers;
            }
    

    And everything works in my case.

    0 讨论(0)
提交回复
热议问题