Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android的OkHttp包處理用戶認證的代碼實例分享

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

編輯:關於Android編程

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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved