Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Volley gives me 400 error

Tags:

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 following code:

String URL = "http://somename/token"; RequestQueue queue = Volley.newRequestQueue(StartActivity.this); queue.add(new JsonObjectRequest(Method.POST, URL, null,    new Listener<JSONObject>() {        @Override        public void onResponse(JSONObject response) {            // handle response            Log.i("StartActivity", response.toString());        }    }, new ErrorListener() {        @Override        public void onErrorResponse(VolleyError error) {            // handle error               Log.i("StartActivity", error.toString());        }    }) {     @Override    public Map<String, String> getHeaders() throws AuthFailureError {        HashMap<String, String> headers = new HashMap<String, String>();        headers.put("username", "someUsername");        headers.put("password", "somePassword");        headers.put("Authorization", "Basic someCodeHere");        return headers;    }    @Override     protected Map<String,String> getParams(){         Map<String,String> params = new HashMap<String, String>();         params.put("grant_type", "client_credentials");              return params;         }    }); 

I get the following error:

02-12 21:42:54.774: E/Volley(19215): [46574] BasicNetwork.performRequest: Unexpected response code 400 for http://somename/token/ 

I have seen a lot of examples and I don't really see what is going wrong here. Anyone any idea?

I updated the code with this method:

HashMap<String, String> createBasicAuthHeader(String username, String password) {         HashMap<String, String> headerMap = new HashMap<String, String>();          String credentials = username + ":" + password;         String base64EncodedCredentials =                 Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);         headerMap.put("Authorization", "Basic " + base64EncodedCredentials);          return headerMap;     } 

and changed getHeaders() to:

@Override    public Map<String, String> getHeaders() throws AuthFailureError {        return createBasicAuthHeader("username", "password");    } 

Still getting the same error!