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

OkHttp 使用完全解析:從同步異步請求到緩存與攔截

編輯:關於 Android 程式設計

一、前言

在 Android 客戶端開發中,網絡請求可謂家常便飯。一般來說,使用 HttpURLConnection 就能滿足需求,但隨著業務邏輯日益複雜,它終究有點力不從心。所幸 Square 開源了一個強大的網絡請求庫——OkHttp。如今 OkHttp 越來越火,OkHttp+Retrofit+RxJava 更是成為主流組合,因此很有必要深入了解它。本文示例代碼主要參考官方 wiki。


二、下載配置

目前最新版本為 3.X,Android 支持 2.3 及以上,若在 Java 應用程序中使用,Java 最低版本為 1.7。既可下載 jar 包引入,也可通過 Maven 獲取:


  com.squareup.okhttp3 okhttp 3.4.1 

或者使用 Gradle:


 compile 'com.squareup.okhttp3:okhttp:3.4.1'

三、基礎使用

同步(Synchronous)Get 請求:


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

OkHttpClient 用於創建請求對象,我們可以通過它配置緩存、超時、代理、攔截器等。大多數情況下,全局只需創建一個實例,讓所有請求共享緩存、連接池與攔截器,如下所示:


 OkHttpClient client = new OkHttpClient.Builder() .readTimeout(8000, TimeUnit.SECONDS) .connectTimeout(8000, TimeUnit.SECONDS) .writeTimeout(8000, TimeUnit.SECONDS) .addInterceptor(new Interceptor()) .cache(cache) .build();

Requests(請求):每個 HTTP 請求包含一個 URL、一個方法(如 GET 或 POST),同時帶有頭信息列表,也可能包含一個描述具體內容的實體數據流。


Responses(響應):根據請求返回響應碼(成功的 200 或未找到的 404)、頭信息以及可選的實體。


Calls(調用):代表一個真實的 HTTP 請求,一般通過兩種方式執行——同步執行 execute(),線程會被鎖住直到響應返回;異步執行 enqueue(),可在任意線程安排請求,並在另一個線程獲得響應回調,不會阻塞當前線程,通過 Callback 對象的成功與失敗方法獲取響應。



以上代碼運行後,前面幾行是響應頭信息。我們可以通過 response.headers() 拿到 Headers 對象,再用索引遍歷獲取頭信息的名稱與值;也可以直接 responseHeaders.get("Cache-Control") 獲取;若某個頭有多個值,可用 public List values(String name) 返回集合,而用 get 方法只會返回最後一個數據。


響應體則通過 response.body() 獲得,調用 string() 可將其轉為字符串。對於小文件,string() 既方便又高效;但若響應實體很大(大於 1 MiB),就要避免使用 string(),因為它會把整個文檔加載進內存,此時更推薦用流來處理實體。


異步(Asynchronous)Get:


 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(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } }); }

以上代碼異步執行,不會阻塞當前線程。該方法接受一個 okhttp3.Callback 對象,請求成功後執行 onResponse,我們可通過 isSuccessful() 判斷響應碼是否在 200 到 300 之間;請求失敗或取消時則回調 onFailure。注意:回調方法都運行在工作線程,不能直接更新 UI。


Accessing Headers(訪問頭信息):典型的 HTTP 頭像一個 Map,每個字段有一個值或沒有;但有些頭允許出現多個值。OkHttp 的 API 兼顧了這兩種情況:寫請求頭時,header(name, value) 會為該 name 設置唯一值(若已存在則刪除後添加新值),addHeader(name, value) 則在不移除已有值的情況下追加新頭。示例如下:


 Request request = new Request.Builder() .url("https://api.github.com/repos/square/okhttp/issues") .header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json") .build();

Posting a String(上傳字符串):


 public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { String postBody = "" + "Releases\n" + "--------\n" + "\n" + " * _1.0_ May 6, 2013\n" + " * _1.1_ June 15, 2013\n" + " * _1.2_ August 11, 2013\n"; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

post 方法接收一個 RequestBody 對象,通過 HTTP POST 把請求實體發送到服務端。由於整個請求實體同時在內存中,因此要避免用它發布大文檔(大於 1 MiB)。


Post 提交鍵值對:本質與上傳表單參數類似,通常用一個 Map 集合傳入即可,無需逐個 add,如下所示:


 private final OkHttpClient client = new OkHttpClient(); public void run(Map params) throws Exception{ FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry entry : params.entrySet()){ builder.add(entry.getKey(),entry.getValue().toString()); } RequestBody formBody = builder.build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

Post 提交 JSON:


 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }

Post Streaming(上傳流):這裡把請求實體作為一個流發布,內容在寫入的過程中逐步產生。示例中的流直接寫入 Okio 緩衝池,若項目更青睞 OutputStream,可通過 BufferedSink.outputStream() 獲取。


 public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_MARKDOWN; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("Numbers\n"); sink.writeUtf8("-------\n"); for (int i = 2; i <= 997; i++) { sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i))); } } private String factor(int n) { for (int i = 2; i < n; i++) { int x = n / i; if (x * i == n) return factor(x) + " × " + i; } return Integer.toString(n); } }; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

Posting a File(上傳文件):使用文件作為請求實體非常簡單。


 public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { File file = new File("README.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

Posting form parameters(上傳表單參數):使用 FormBody.Builder 構建的請求實體,工作起來就像一個 HTML 標簽,名稱與值會以 HTML 兼容的 URL 編碼方式處理。


 private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

Posting a multipart request(上傳多部分請求):MultipartBody.Builder 可以構建兼容 HTML 文件上傳表單的複雜請求實體,每個部分本身也是一個請求實體,可定義自己的頭信息;若合適,內容長度與內容類型頭會被自動添加。


 private static final String IMGUR_CLIENT_ID = "..."; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", "Square Logo") .addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build(); Request request = new Request.Builder() .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url("https://api.imgur.com/3/image") .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }

設置 setType 時一般取 MultipartBody.FORM;addFormDataPart(String name, String value) 可添加鍵值對,addFormDataPart(String name, String filename, RequestBody body) 可添加文件;addPart 提供了三個重載方法,其中 addPart(Headers headers, RequestBody body) 允許在添加 RequestBody 的同時單獨設置請求頭。


 RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart(Headers.of("Content-Disposition", "form-data; name=\"username\""), RequestBody.create(null, "test")) .build();

Parse a JSON Response With Gson(用 Gson 解析 JSON 響應):Gson 是能在 JSON 與 Java 對象之間便捷互轉的 API,這裡用它解析來自 GitHub API 的 JSON 響應。


 private final OkHttpClient client = new OkHttpClient(); private final Gson gson = new Gson(); public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gson.fromJson(response.body().charStream(), Gist.class); for (Map.Entry entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } } static class Gist { Map files; } static class GistFile { String content; }

用法與平時並無二致。


Response Caching(響應緩存):緩存是我們常用的功能,示例代碼如下:


 private final OkHttpClient client; public CacheResponse(File cacheDirectory) throws Exception { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(cacheDirectory, cacheSize); client = new OkHttpClient.Builder() .cache(cache) .build(); } public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); Response response1 = client.newCall(request).execute(); if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); String response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); }

要啟用緩存,你需要一個可讀寫且限制大小的緩存目錄,且該目錄應當私有,不受信任的應用不應讀取其內容。因此我們一般這樣配置,把緩存數據放到 context.getCacheDir() 的子目錄中:


 final @Nullable File baseDir = context.getCacheDir(); if (baseDir != null) { final File cacheDir = new File(baseDir, "HttpResponseCache"); okHttpClient.setCache(new Cache(cacheDir, 10 * 10 * 1024)); }

第一次請求完成後,OkHttp 會把結果寫入緩存:此時 response1.networkResponse() 為網絡請求值,response1.cacheResponse() 為 null;第二次則相反,response2.cacheResponse() 是第一次的網絡值,response2.networkResponse() 為 null,說明第二次命中了緩存,兩次 body 相等也印證了這一點。此外,配置響應頭 Cache-Control:max-stale=3600 或 Cache-Control: max-age=9600,OkHttp 也會按時間進行緩存處理,超時後重新走網絡。若希望禁止緩存、只取網絡,可用 CacheControl.FORCE_NETWORK;若希望只用緩存、不走網絡,可用 CacheControl.FORCE_CACHE。注意:若用 FORCE_CACHE 而緩存不存在,OkHttp 會返回 504 無法滿足的響應。


Canceling a Call(取消調用):當 Activity 退出時,可用 Call.cancel() 立即中止一個正在進行的調用;若某線程正在寫請求或讀響應,它會收到一個 IOException。下面的示例中,服務端有兩秒延遲,客戶端在發出請求 1 秒後將其取消,於是拋出 IOException。


 private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("https://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build(); final long startNanos = System.nanoTime(); final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. executor.schedule(new Runnable() { @Override public void run() { System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); call.cancel(); System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); } }, 1, TimeUnit.SECONDS); try { System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); Response response = call.execute(); System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); } catch (IOException e) { System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); } }

Timeouts(超時):訪問服務器通常分為三段——客戶端與服務端建立連接 connectTimeout、客戶端向服務端發送數據 writeTimeout、服務端把數據回傳客戶端 readTimeout,每一步都可能耗時,因此設置超時非常有必要,一旦超過某段時間就拋出異常。


 private final OkHttpClient client; public ConfigureTimeouts() throws Exception { client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); } public void run() throws Exception { Request request = new Request.Builder() .url("https://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build(); Response response = client.newCall(request).execute(); System.out.println("Response completed: " + response); }

Per-call Configuration(每次調用的配置):所有 HTTP 客戶端配置都集中在 OkHttpClient 中,包括代理、超時與緩存。當你只想為單個調用調整配置時,可調用 OkHttpClient.newBuilder(),它會返回一個共享相同連接池、分配器與原始配置的 builder。下面的示例中,一個請求設置 500ms 超時,另一個設置 3000ms 超時。


 private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("https://httpbin.org/delay/1") // This URL is served with a 1 second delay. .build(); try { // Copy to customize OkHttp for this request. OkHttpClient copy = client.newBuilder() .readTimeout(500, TimeUnit.MILLISECONDS) .build(); Response response = copy.newCall(request).execute(); System.out.println("Response 1 succeeded: " + response); } catch (IOException e) { System.out.println("Response 1 failed: " + e); } try { // Copy to customize OkHttp for this request. OkHttpClient copy = client.newBuilder() .readTimeout(3000, TimeUnit.MILLISECONDS) .build(); Response response = copy.newCall(request).execute(); System.out.println("Response 2 succeeded: " + response); } catch (IOException e) { System.out.println("Response 2 failed: " + e); } }

Handling authentication(處理身份驗證):OkHttp 可以自動重試未經認證的請求。當響應為 401 未授權時,會訪問 Authenticator 來提供憑證,實現方式是建立一個包含缺失憑證的新請求;若無憑證可用,返回 null 以跳過重試。


 private final OkHttpClient client; public Authenticate() { client = new OkHttpClient.Builder() .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { 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(); } }) .build(); } public void run() throws Exception { 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()); }

若用戶名或密碼有誤,OkHttp 會一直用這個錯誤信息重試,因此我們應加一個判斷:若之前已用該憑證失敗過,就不應再次嘗試:


 if (credential.equals(response.request().header("Authorization"))) { return null; // If we already failed with these credentials, don't retry. }

當你想設置應用定義的重試上限時,也可以跳過重試:


 if (responseCount(response) >= 3) { return null; // If we've failed 3 times, give up. }

上述代碼依賴於 responseCount() 方法:


 private int responseCount(Response response) { int result = 1; while ((response = response.priorResponse()) != null) { result++; } return result; }

四、總結

OkHttp 十分強大,跟著 wiki 走一遍基本就能上手。下一篇筆者將講解攔截器與 OkHttp 的封裝,讓調用更加簡潔。

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