Alok
Alok

Reputation: 297

BasicNetwork.performRequest - Unexpected response code 400 (POST)

When I am trying to fetch data through rest api using Volley StringRequest or JsonObjectRequest. I always get 400 error. Its working fine with the postman. Http request method is POST, Content-Type is application/x-www-form-urlencoded. I have also checked my parameter spelling and it looks fine to me. I have tried with both StringRequest and JsonObjectRequest, result is E/Volley: [10283] BasicNetwork.performRequest: Unexpected response code 400. Below is my code. I have attached a screenshot.

enter image description here

Here is the new screenshot Error in code

StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response.toString());
                    viewHelper.hideDialog();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, error.toString());
                    viewHelper.hideDialog();
                }
            }){
                @Override
                protected Map<String, String> getParams() {
                    // Posting parameters to login url
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("grant_type", "password");
                    params.put("username", email);
                    params.put("password", password);
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/x-www-form-urlencoded");
                    return params;
                }

                @Override
                public String getBodyContentType(){
                    return "application/x-www-form-urlencoded";
                }
            };

            stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");

I have alos tried with volley JSONObjectRequest

            Map<String, String> params = new HashMap<String, String>();
            params.put("grant_type", "password");
            params.put("username", email);
            params.put("password", password);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/x-www-form-urlencoded");
                    return headers;
                }
            };

Can anyone please help me in fixing this issue.

Upvotes: 2

Views: 9042

Answers (3)

Alok
Alok

Reputation: 297

Below is the working example of POST request using Volley library.
Add this to your build.gradle (Module:app) - compile 'com.mcxiaoke.volley:library:1.0.19'

StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response.toString());
                    progressDialog.dismiss();

                    JSONObject jsonObject = null;

                    try {
                        jsonObject = new JSONObject(response);

                        if(jsonObject.has("success")){
                            if(jsonObject.getBoolean("success") == true){
                                JSONObject userObject = new JSONObject(jsonObject.getString("user"));

                                Map<String, String> loginDetails = new HashMap<String, String>();
                                loginDetails.put(KEY_IS_LOGGED_IN, "true");
                                loginDetails.put(ACCESS_TOKEN, jsonObject.getString(ACCESS_TOKEN));
                                loginDetails.put(USERID, userObject.getString(USERID));
                                loginDetails.put(FIRSTNAME, userObject.getString(FIRSTNAME));
                                loginDetails.put(LASTNAME, userObject.getString(LASTNAME));
                                loginDetails.put(EMAIL, userObject.getString(EMAIL));

                                session = new SessionManager(_myActivity);
                                session.setLogin(loginDetails);

                                Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
                                intent.putExtra("FROM_ACTIVITY", "LoginActivity");
                                startActivity(intent);
                                LoginActivity.this.finish();
                            }else{
                                btnLogin.setClickable(true);
                                btnLogin.setEnabled(true);
                                Toast.makeText(getApplicationContext(), "Username or Password does not matched!", Toast.LENGTH_LONG).show();
                            }
                        }

                    } catch (JSONException e) {
                        btnLogin.setClickable(true);
                        btnLogin.setEnabled(true);
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Something went wrong, Please try agian", Toast.LENGTH_LONG).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, error.toString());
                    progressDialog.dismiss();

                    btnLogin.setClickable(true);
                    btnLogin.setEnabled(true);
                }
            }){
                @Override
                protected Map<String, String> getParams() {
                    // Posting parameters to login url
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("grant_type", "password");
                    params.put("username", email);
                    params.put("password", password);
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/x-www-form-urlencoded");
                    return params;
                }

                @Override
                public String getBodyContentType(){
                    return "application/x-www-form-urlencoded";
                }
            };

            stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            // Adding request to request queue
            RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());

            mRequestQueue.add(stringRequest);

Please comment if anyone faced issue with above code.
Thanks to everyone who tried to help me.

Upvotes: 3

rafsanahmad007
rafsanahmad007

Reputation: 23881

Unexpected response code 400 means Bad Reuest.

This Response is caused by sending wrong parameters with the URL.

To solve:

  1. Check every parameter with spelling.

  2. Make sure if response is obtained in string or in object. stringRequest or JSONObjectReuest

  3. Also check Content-type

use this as Content-type

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

For JsonObjectReuest use:

 HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "BLah");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
   @Override
   public void onResponse(JSONObject response) {
       try {
           Log.d("Response:", response.toString());
       } catch (JSONException e) {
           e.printStackTrace();
       }
   }
}, new Response.ErrorListener() {
   @Override
   public void onErrorResponse(VolleyError error) {
       Log.d("Error: ", error.getMessage());
   }
});

Upvotes: 0

Nikhil Sharma
Nikhil Sharma

Reputation: 603

A 400 means bad request the data sent by the you to the server didn't follow the rules.So check your parameter or spelling of these parameter which is required by server. So check those try again hope it work for you :)

Upvotes: 1

Related Questions