Http Authentication in android using volley library

只愿长相守 提交于 2020-01-14 09:06:07

问题


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);

回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/17905669/http-authentication-in-android-using-volley-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!