欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-04 13:44:29
okhttp 提供了对用户认证的支持。当 http 响应的状态代码是 401 时,okhttp 会从设置的 authenticator 对象中获取到新的 request 对...

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());
}