使用Volley库在android中进行Http身份验证 [英] Http Authentication in android using volley library
问题描述
如何使用 Volley库为API进行 Http身份验证?
我尝试了以下代码....它引发运行时异常&空指针异常..请提供建议
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);
基本的Http授权看起来像下一个标头:
Authorization: Basic dXNlcjp1c2Vy
其中dXNlcjp1c2Vy是您的user:password字符串,格式为 Base64 ,单词"Basic"表示授权类型.
>因此,您需要设置名为Authorization的请求标头.
为此,您需要在请求类中覆盖getHeaders方法
代码如下:
@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;
}
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);
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;
}
这篇关于使用Volley库在android中进行Http身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!