使用volley库在android中进行Http身份验证

时间:2013-07-28 06:36:20

标签: android http-authentication android-networking android-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);

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:4)

扩展您选择的排球请求类并覆盖getHeaders()。返回带有身份验证信息的Map(headers.put('Authorization','authinfo ...'))