編輯:關於 Android 程式設計
HTTP 標頭是請求與回應中的重要組成部分。建立請求時需要設定標頭,收到回應後也常需要解析其中的標頭。本文說明 OkHttp 的標頭操作 API,並示範同步與非同步 GET 下載。
從程式碼角度看,HTTP 標頭的資料結構是 Map<String, List<String>>——每個標頭名稱可能對應多個值。不過大部分標頭只有單一值,只有少部分(例如 Set-Cookie)允許多值。OkHttp 用一組簡單的方法區分這兩種情況,讓操作更直覺:
設定標頭時,header(name, value) 會設定該標頭的唯一值,對同一標頭多次呼叫會覆蓋先前設定的值;addHeader(name, value) 則是新增一個值。
讀取標頭時,header(name) 回傳該標頭最後出現的值(單值時即為該值,多值時回傳最後一筆);headers(name) 則回傳所有值。
public class Headers {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.header("User-Agent", "My super agent")
.addHeader("Accept", "text/html")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("服務器端錯誤: " + response);
}
System.out.println(response.header("Server"));
System.out.println(response.headers("Set-Cookie"));
}
}
這裡用 header() 設定了 User-Agent,用 addHeader() 加上 Accept;解析時以 header() 取出 Server 的單一值,以 headers() 取出 Set-Cookie 的所有值。
下載檔案,印出回應標頭與內容本體。String() 方法對小檔案非常方便且高效,但若是大型檔案(大於 1MB),應盡量避免使用,因為它會把整份文字載入記憶體。這種情況的正確做法是把回應本體當作串流來處理。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
在工作執行緒中執行下載,並在回應抵達時以回呼方式通知。這個回呼會在回應標頭準備好之後送出,因此讀取標頭仍會阻塞。目前 OkHttp 尚未提供非同步接收部分回應本體的 API。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
在 Android 中使用時有兩點要特別注意。第一,enqueue() 的回呼是在 OkHttp 自己的執行緒上觸發,不在主執行緒,因此若要更新 UI,必須切換回主執行緒。第二,Response 與 ResponseBody 必須關閉,否則會造成連線洩漏;最簡便的做法是搭配 try (Response response = ...) 的 try-with-resources 寫法。
另外,OkHttp 4.x 已移除 response.isSuccessful() 之外的一些舊寫法並改用 Kotlin 實作,enqueue 的 Callback 介面寫法則維持不變。若專案使用新版,從 Java 呼叫時仍可沿用以上範例。