編輯:關於 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 時,使用 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(...) 的建構者模式,較為明確且不依賴實作細節。
NoHttp 源碼解析(一):請求模組全拆解
市面上的 Http 框架很多,上層的有 NoHttp、Retrofit、Volley、android-async-http,底層的有 HttpURLConnection、
動手驗證 Android 四種 Activity 啟動模式
網路上談啟動模式的文章很多,但內容往往互相抄襲,讀下來似懂非懂。直到看了《Android 開發藝術探索》,才發現自己過去的理解實在太淺。於是決定親手把四種啟動模式一個個驗
如何在 Android 中實現漸顯按鈕的左右滑動效果
本範例要做的效果是:左右兩側各有一個浮動箭頭按鈕,平常隱藏,手指觸碰螢幕時漸顯,放開後淡出。頁面本身則用 ViewFlipper 承載多張圖片,可左右切換。 專案結
Android ListView 與 ExpandableListView 實現多選、單選、全選與批量輸入
下圖為列表多選與批量輸入的示意。 ListView 多選與全選 在 Adapter 中可用 Map 或 SparseArray 記錄每一列的勾選狀態。getView 時