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);
4

2 回答 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;
}
于 2014-10-10T14:33:39.857 回答
4

Extend the volley request class of your choice and overwrite getHeaders(). Return a Map with the authentication information there (headers.put('Authorization', 'authinfo...'))

于 2013-07-28T23:18:22.923 回答