OkHttp 上手
優點
- 快、節省帶寬。
- 支持 HTTP/2 和 SPDY。
- HTTP/2 和 SPDY 允許對同一個主機的所有請求,使用一個 socket。
- 如果不支持 SPDY 的話,可以用連接池減少請求等待時間。
- GZIP 縮小傳輸大小。
- 緩存響應(response caching)徹底避免重復請求。
- 網絡異常時重試。
- 如果服務有多個 ip ,如果第一個 ip 鏈接失敗時 OkHttp 會嘗試切換到其他 ip 。
failover
- OkHttp 2.0 API 支持同步阻塞式調用(synchronous blocking calls)和異步回調(async calls with callbacks)。
- 不需要重寫網絡相關代碼就可以試用 OkHttp 。
okhttp-urlconnection
模塊實現了常用的java.net.HttpURLConnection
的API,okhttp-apache
模塊實現了 ApacheHttpClient
的 API 。
Calls
- 支持重定向(302)等。
默認自動
重定向。 - 如果 resposne 提出驗證權限,OkHttp 會向
Authenticator
詢問權限。 - 請求分為同步和異步
- Synchronous:your thread blocks until the response is readable.
- Asynchronous:you enqueue the request on any thread, and get called back on another thread when the response is readable.
- 請求可以從任何線程取消。如果取消時正在“writing the request body”或“reading the response body”,會收到一個 IOExceptioin 。
Connections
- 沒讀懂。
Recipes(菜譜)
- 默認是不緩存的。想要緩存響應(responses)的話,需要制定緩存目錄和緩存大小。并且需要有 ETag 之類的 header 配合。 Response Caching
interceptors
- Interceptors 分為
Application Interceptors
和Network Interceptors
。 - Interceptors 可以是一系列的。(Interceptors can be chained.)按順序執行。
- 一般在 Interceptors 中做這些:
- 壓縮
- 處理 http header
- 打印日志
- ...
- 如果自動重定向的話(302等),Network Interceptors 能攔截到兩次,Application Intercepors 只能攔截到一次。因為重定向是在
OkHttp Core
中執行的。
HTTPS
還沒看!