在Android中使用Volley库进行HTTP身份验证

6
如何使用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);

您可以使用droidQuery来执行带有身份验证的异步RESTful请求。请查看AjaxOptions文档,以添加用户名和密码到请求中。 - Phil
2个回答

9

基本的 Http 认证看起来像下面的头部信息:

Authorization: Basic dXNlcjp1c2Vy

其中dXNlcjp1c2Vy是你的用户:密码字符串,格式为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;
}

4

扩展您选择的Volley请求类并覆盖getHeaders()。在那里返回一个包含身份验证信息的Map(headers.put('Authorization', 'authinfo...'))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接