问题
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