亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

OkHttp 提供了對用戶認(rèn)證的支持。當(dāng) HTTP 響應(yīng)的狀態(tài)代碼是 401 時,OkHttp 會從設(shè)置的 Authenticator 對象中獲取到新的 Request 對象并再次嘗試發(fā)出請求。Authenticator 接口中的 authenticate 方法用來提供進(jìn)行認(rèn)證的 Request 對象,authenticateProxy 方法用來提供對代理服務(wù)器進(jìn)行認(rèn)證的 Request 對象。
用戶認(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)一個 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());
}

相關(guān)文章

最新評論