Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

OkHttp 實作用戶認證(Authenticator)的完整寫法

編輯:關於 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;
    }
});

回傳 null 代表放棄本次認證嘗試,OkHttp 會把 401 回應交回呼叫方處理。

進階:處理 Basic Challenge

當需要實作一個 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 表示不嘗試代理認證
        }
    });

    Request request = new Request.Builder()
            .url("https://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());
}

兩個容易出錯的地方

第一,避免無限重試。如果伺服器始終回傳 401,而 authenticate 每次都回傳新的 Request,就會形成無窮迴圈。實務上應加入重試次數計數,超過上限後回傳 null:

private int responseCount = 0;

@Override
public Request authenticate(Proxy proxy, Response response) {
    if (responseCount >= 3) {
        return null;  // 超過重試上限,放棄
    }
    responseCount++;
    String credential = Credentials.basic("jesse", "password1");
    return response.request().newBuilder()
            .header("Authorization", credential)
            .build();
}

第二,注意 Authenticator 的呼叫時機。它只在收到 401(或代理的 407)時才被觸發,並非每個請求都會經過。若希望「每個請求都帶上 token」,應該改用 Interceptor 搭配 addInterceptor(),而不是 Authenticator。兩者的分工是:Interceptor 主動附加憑證,Authenticator 在被拒絕後補救。

另外提醒,OkHttp 4.x 已改用 Kotlin 實作,client.setAuthenticator() 這種 setter 寫法在 Java 中是直接對欄位赋值,新版本應改用 OkHttpClient.Builder().authenticator(...) 的建構者模式,較為明確且不依賴實作細節。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved