当前位置: 移动技术网 > 移动技术>移动开发>Android > Android的OkHttp包处理用户认证的代码实例分享

Android的OkHttp包处理用户认证的代码实例分享

2019年07月24日  | 移动技术网移动技术  | 我要评论

okhttp 提供了对用户认证的支持。当 http 响应的状态代码是 401 时,okhttp 会从设置的 authenticator 对象中获取到新的 request 对象并再次尝试发出请求。authenticator 接口中的 authenticate 方法用来提供进行认证的 request 对象,authenticateproxy 方法用来提供对代理服务器进行认证的 request 对象。
用户认证的示例:

okhttpclient client = new okhttpclient();
client.setauthenticator(new authenticator() {
public request authenticate(proxy proxy, response response) throws ioexception {
  string credential = credentials.basic("user", "password");
  return response.request().newbuilder()
      .header("authorization", credential)
      .build();
}

public request authenticateproxy(proxy proxy, response response) 
throws ioexception {
  return null;
}
});

进阶
当需要实现一个 basic challenge, 使用 credentials.basic(username, password) 来编码请求头。

private final okhttpclient client = new okhttpclient();

public void run() throws exception {
 client.setauthenticator(new authenticator() {
  @override public request authenticate(proxy proxy, response response) {
   system.out.println("authenticating for response: " + response);
   system.out.println("challenges: " + response.challenges());
   string credential = credentials.basic("jesse", "password1");
   return response.request().newbuilder()
     .header("authorization", credential)
     .build();
  }

  @override public request authenticateproxy(proxy proxy, response response) {
   return null; // null indicates no attempt to authenticate.
  }
 });

 request request = new request.builder()
   .url("http://publicobject.com/secrets/hellosecret.txt")
   .build();

 response response = client.newcall(request).execute();
 if (!response.issuccessful()) throw new ioexception("unexpected code " + response);

 system.out.println(response.body().string());
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网