轉(zhuǎn)載請注明出處 http://m.itdecent.cn/p/fc4d4348dc58 (作者:韓棟)
本文為譯文,由于譯者水平有限,歡迎拍磚,讀者也可以閱讀原文
【OkHttp3-基本用法,OkHttp3-使用進階(Recipes),OkHttp3-請求器(Calls),OkHttp3-連接(Connections),OkHttp3-攔截器(Interceptor)】
攔截器
攔截器是OkHttp中提供一種強大機制,它可以實現(xiàn)網(wǎng)絡(luò)監(jiān)聽、請求以及響應(yīng)重寫、請求失敗重試等功能。下面舉一個簡單打印日志的栗子,此攔截器可以打印出網(wǎng)絡(luò)請求以及響應(yīng)的信息。
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
在沒有本地緩存的情況下,每個攔截器都必須至少調(diào)用chain.proceed(request)一次,這個簡單的方法實現(xiàn)了Http請求的發(fā)起以及從服務(wù)端獲取響應(yīng)。
攔截器可以進行鏈式處理。假如你同時有一個壓縮數(shù)據(jù)和校驗數(shù)據(jù)的攔截器,你可以決定將請求或者響應(yīng)數(shù)據(jù)先進行壓縮還是先校驗大小。OkHttp利用List集合去跟蹤并且保存這些攔截器,并且會依次遍歷調(diào)用。

Application interceptors
攔截器可以以application或者network兩種方式注冊,分別調(diào)用addInterceptor()以及addNetworkInterceptor方法進行注冊。我們使用上文中日志攔截器的使用來體現(xiàn)出兩種注冊方式的不同點。
首先通過調(diào)用addInterceptor()在OkHttpClient.Builder鏈式代碼中注冊一個application攔截器:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://www.publicobject.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();
請求的URLhttp://www.publicobject.com/helloworld.txt被重定向成https://publicobject.com/helloworld.txt,OkHttp支持自動重定向。注意,我們的application攔截器只會被調(diào)用一次,并且調(diào)用chain.proceed()之后獲得到的是重定向之后的最終的響應(yīng)信息,并不會獲得中間過程的響應(yīng)信息:
INFO: Sending request http://www.publicobject.com/helloworld.txt on null
User-Agent: OkHttp Example
INFO: Received response for https://publicobject.com/helloworld.txt in 1179.7ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
我們可以看到請求的URL被重定向了,因為response.request().url()和request.url()是不一樣的。日志打印出來的信息顯示兩個不同的URL??蛻舳说谝淮握埱髨?zhí)行的url為http://www.publicobject.com/helloworld.txt,而響應(yīng)數(shù)據(jù)的url為https://publicobject.com/helloworld.txt。
Network interceptors
注冊一個Network攔截器和注冊Application攔截器方法是非常相似的。注冊Application攔截器調(diào)用的是addInterceptor(),而注冊Network攔截器調(diào)用的是addNetworkInterceptor()。
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder()
.url("http://www.publicobject.com/helloworld.txt")
.header("User-Agent", "OkHttp Example")
.build();
Response response = client.newCall(request).execute();
response.body().close();
我們運行這段代碼,發(fā)現(xiàn)這個攔截被執(zhí)行了兩次。一次是初始化也就是客戶端第一次向URL為http://www.publicobject.com/helloworld.txt發(fā)出請求,另外一次則是URL被重定向之后客戶端再次向https://publicobject.com/helloworld.txt發(fā)出請求。
INFO: Sending request http://www.publicobject.com/helloworld.txt on Connection{www.publicobject.com:80, proxy=DIRECT hostAddress=54.187.32.157 cipherSuite=none protocol=http/1.1}
User-Agent: OkHttp Example
Host: www.publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip
INFO: Received response for http://www.publicobject.com/helloworld.txt in 115.6ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: https://publicobject.com/helloworld.txt
INFO: Sending request https://publicobject.com/helloworld.txt on Connection{publicobject.com:443, proxy=DIRECT hostAddress=54.187.32.157 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1}
User-Agent: OkHttp Example
Host: publicobject.com
Connection: Keep-Alive
Accept-Encoding: gzip
INFO: Received response for https://publicobject.com/helloworld.txt in 80.9ms
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/plain
Content-Length: 1759
Connection: keep-alive
NetWork請求包含了更多信息,比如OkHttp為了減少數(shù)據(jù)的傳輸時間以及傳輸流量而自動添加的請求頭Accept-Encoding: gzip希望服務(wù)器能返回經(jīng)過壓縮過的響應(yīng)數(shù)據(jù)。Network 攔截器調(diào)用Chain方法后會返回一個非空的Connection對象,它可以用來查詢客戶端所連接的服務(wù)器的IP地址以及TLS配置信息。
選擇使用Application或Network攔截器?
每一個攔截器都有它的優(yōu)點。
Application interceptors
- 無法操作中間的響應(yīng)結(jié)果,比如當(dāng)URL重定向發(fā)生以及請求重試等,只能操作客戶端主動第一次請求以及最終的響應(yīng)結(jié)果。
- 在任何情況下只會調(diào)用一次,即使這個響應(yīng)來自于緩存。
- 可以監(jiān)聽觀察這個請求的最原始未經(jīng)改變的意圖(請求頭,請求體等),無法操作OkHttp為我們自動添加的額外的請求頭,比如
If-None-Match。 - 允許
short-circuit (短路)并且允許不去調(diào)用Chain.proceed()。(編者注:這句話的意思是Chain.proceed()不需要一定要調(diào)用去服務(wù)器請求,但是必須還是需要返回Respond實例。那么實例從哪里來?答案是緩存。如果本地有緩存,可以從本地緩存中獲取響應(yīng)實例返回給客戶端。這就是short-circuit (短路)的意思。。囧) - 允許請求失敗重試以及多次調(diào)用
Chain.proceed()。
Network Interceptors
- 允許操作中間響應(yīng),比如當(dāng)請求操作發(fā)生重定向或者重試等。
- 不允許調(diào)用緩存來
short-circuit (短路)這個請求。(編者注:意思就是說不能從緩存池中獲取緩存對象返回給客戶端,必須通過請求服務(wù)的方式獲取響應(yīng),也就是Chain.proceed()) - 可以監(jiān)聽數(shù)據(jù)的傳輸
- 允許
Connection對象裝載這個請求對象。(編者注:Connection是通過Chain.proceed()獲取的非空對象)
重寫請求
攔截器可以添加、移除或者替換請求頭。甚至在有請求主體時候,可以改變請求主體。舉個栗子,你可以使用application interceptor添加經(jīng)過壓縮之后的請求主體,當(dāng)然,這需要你將要連接的服務(wù)端支持處理壓縮數(shù)據(jù)。
/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
final class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
重寫響應(yīng)
和重寫請求相似,攔截器可以重寫響應(yīng)頭并且可以改變它的響應(yīng)主體。相對于重寫請求而言,重寫響應(yīng)通常是比較危險的一種做法,因為這種操作可能會改變服務(wù)端所要傳遞的響應(yīng)內(nèi)容的意圖。
當(dāng)然,如果你 比較奸詐 在不得已的情況下,比如不處理的話的客戶端程序接受到此響應(yīng)的話會Crash等,以及你還可以保證解決重寫響應(yīng)后可能出現(xiàn)的問題時,重新響應(yīng)頭是一種非常有效的方式去解決這些導(dǎo)致項目Crash的問題。舉個栗子,你可以修改服務(wù)器返回的錯誤的響應(yīng)頭Cache-Control信息,去更好地自定義配置響應(yīng)緩存保存時間。
/** Dangerous interceptor that rewrites the server's cache-control header. */
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", "max-age=60")
.build();
}
};
不過通常最好的做法是在服務(wù)端修復(fù)這個問題。