sony sony -4 years ago 153
Android Question

Send authentication information with volley request

In my android app I have to call a web service which looks like this

http://mywesite.com/demo/mob/getmenubycategory/1


I am using the volley to send the request but the result is
VolleyError 401
.
I have overridden the
getParams()
method to add the header. but it is not working.
Here is my code.

RequestQueue requestQueue = volleySingleton.getRequestQueue();
requestQueue.add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e(TAG, "onResponse = \n " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "response error \n" + error.networkResponse.statusCode);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
try {
Map<String, String> map = new HashMap<String, String>();
String key = "Authorization";
String encodedString = Base64.encodeToString(String.format("%s:%s", "USERNAME", "Password").getBytes(), Base64.NO_WRAP);
String value = String.format("Basic %s", encodedString);
map.put(key, value);
return map;
} catch (Exception e) {
Log.e(TAG, "Authentication Filure" );
}
return super.getParams();
}
});


When i use my browser it shows a dialogue to enter my username and password. How can i send the username and password with the request using volley.
Any help to solve this will be appreciated.

Answer Source

For authentication, IMHO, you should override getHeaders instead of getParams, please try the following:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
       Map<String, String> headers = new HashMap<>();                
       String credentials = "username:password";
       String auth = "Basic "
                        + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
       headers.put("Content-Type", "application/json");
       headers.put("Authorization", auth);
       return headers;
}

Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download