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

Android的OkHttp包處理用戶認證的代碼實例分享

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

OkHttp 提供了對用戶認證的支持。當 HTTP 響應的狀態(tài)代碼是 401 時,OkHttp 會從設置的 Authenticator 對象中獲取到新的 Request 對象并再次嘗試發(fā)出請求。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;
}
});

進階
當需要實現(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());
}

相關文章

最新評論