使用Volley库在android中进行Http身份验证 [英] Http Authentication in android using volley library

查看:197
本文介绍了使用Volley库在android中进行Http身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆