Http Authentication in android using volley library
Asked Answered
D

2

6

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);
Dric answered 28/7, 2013 at 6:36 Comment(1)
You can use droidQuery to perform async restful requests with authentication. Look at the AjaxOptions documentation for adding a username and password to a request.Treasatreason
R
9

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;
}
Randalrandall answered 10/10, 2014 at 14:33 Comment(0)
C
4

Extend the volley request class of your choice and overwrite getHeaders(). Return a Map with the authentication information there (headers.put('Authorization', 'authinfo...'))

Carper answered 28/7, 2013 at 23:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.