Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http Authentication in android using volley library

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);
like image 591
Dharani Kumar Avatar asked Jul 28 '13 06:07

Dharani Kumar


1 Answers

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;
}
like image 138
Sergey Pekar Avatar answered Nov 16 '22 22:11

Sergey Pekar