欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android的OkHttp包處理用戶認(rèn)證的代碼實(shí)例分享

 更新時(shí)間:2016年07月13日 16:00:48   作者:成富  
OkHttp包(GitHub主頁github.com/square/okhttp)是一款高人氣安卓HTTP支持包,這里我們來看一下Android的OkHttp包處理用戶認(rèn)證的代碼實(shí)例分享:

OkHttp 提供了對(duì)用戶認(rèn)證的支持。當(dāng) HTTP 響應(yīng)的狀態(tài)代碼是 401 時(shí),OkHttp 會(huì)從設(shè)置的 Authenticator 對(duì)象中獲取到新的 Request 對(duì)象并再次嘗試發(fā)出請(qǐng)求。Authenticator 接口中的 authenticate 方法用來提供進(jìn)行認(rèn)證的 Request 對(duì)象,authenticateProxy 方法用來提供對(duì)代理服務(wù)器進(jìn)行認(rèn)證的 Request 對(duì)象。
用戶認(rèn)證的示例:

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

進(jìn)階
當(dāng)需要實(shí)現(xiàn)一個(gè) Basic challenge, 使用 Credentials.basic(username, password) 來編碼請(qǐng)求頭。

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

相關(guān)文章

最新評(píng)論