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

Dha*_*mar 6 android http-authentication android-networking android-volley

如何使用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);
Run Code Online (Sandbox Code Playgroud)

Ser*_*kar 9

基本的Http授权看起来像下一个标题:

Authorization: Basic dXNlcjp1c2Vy
Run Code Online (Sandbox Code Playgroud)

其中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;
}
Run Code Online (Sandbox Code Playgroud)


Mak*_*ibo 4

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