Http Authentication in android using volley library

Dharani Kumar picture Dharani Kumar · Jul 28, 2013 · Viewed 9.5k times · Source

How to make Http Authentication for API using Volley library ?

I tried the following code ....it throws Runtime Exception & Null pointer exception..Please provide suggestions

String url = "Site url";
String host = "hostName";
int port = 80;
String userName = "username";
String password = "Password";
DefaultHttpClient client = new DefaultHttpClient();
AuthScope authscope = new AuthScope(host, port);
Credentials credentials = new UsernamePasswordCredentials(userName, password);
client.getCredentialsProvider().setCredentials(authscope, credentials);
HttpClientStack stack = new HttpClientStack(client);
RequestQueue queue =  Volley.newRequestQueue(VolleyActivity.this, stack);

Answer

Sergey  Pekar picture Sergey Pekar · Oct 10, 2014

Basic Http authorization looks like the next header:

Authorization: Basic dXNlcjp1c2Vy

where dXNlcjp1c2Vy is your user:password string in Base64 format, word "Basic" means the authorization type.

So you need to set the request header named Authorization.

To do this you need to override getHeaders method in your request class

The code will look like this:

@Override
public Map<String, String> getHeaders() {
    Map<String, String> params = new HashMap<String, String>();
    params.put(
            "Authorization",
            String.format("Basic %s", Base64.encodeToString(
                    String.format("%s:%s", "username", "password").getBytes(), Base64.DEFAULT)));
    return params;
}