攔截器是很有用的機制,它可以監(jiān)控,改寫邦蜜,和重試call。下面的例子展示了通過攔截器打印request啰挪,response的日志。
class LoggingInterceptor implements Interceptor {
@Override public Response interceptor (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;
}
}
對每個攔截器的實現(xiàn)來說<code>chain.proceed(request)</code>都是重要的部分嘲叔,這個看起來簡單的方法保證了HTTP的工作亡呵。產(chǎn)生一個request的response。
攔截器可以被鏈接硫戈。假設(shè)你有一個壓縮攔截器和一個校驗攔截器:你可以決定先壓縮后校驗锰什,還是先校驗在壓縮。OkHttp通過list跟蹤攔截器丁逝,并按照順序調(diào)用歇由。
Application Interceptors
攔截器既可以作為應(yīng)用攔截器也可以作為網(wǎng)絡(luò)攔截器。我們將使用上面定義的<code>LoggingInterceptor</code>展示他們的不同果港。
通過調(diào)用<code>addInterceptor()</code>在<code>OkHttpClient.Builder</code>上添加一個應(yīng)用攔截器:
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();
URL <code>http://www.publicobject.com/helloworld.txt</code>
將被重定向到
<code>https://www.publicobject.com/helloworld.txt</code>,
OkHttp 將自動重定向。我們的應(yīng)用攔截器只調(diào)用了一次而且<code>chain.proceed()</code>返回的是最終的response糊昙。
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
可以看到重定向發(fā)生了 因為請求的地址和響應(yīng)的地址不同辛掠,這兩個日志展示了兩個不同的URL
Network Interceptors
注冊一個網(wǎng)絡(luò)過濾器也大致相同,通過<code>addNetWorkInterceptor()</code>方法而不是<code>addInterceptor()</code>:
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();
當我們運行這段代碼的時候這個攔截器將運行兩次释牺。一次是初始request
<code>http://www.publicobject.com/helloworld.txt</code>萝衩,
另一次是重定向
<code>https://www.publicobject.com/helloworld.txt</code>
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
網(wǎng)絡(luò)請求包含更多的數(shù)據(jù)。例如OkHttp添加<code>Accept-Encoding: gzip</code>頭告知服務(wù)器支持response壓縮没咙。網(wǎng)絡(luò)攔截器的<code>Chain</code>包含一個非空<code>Connection</code>可以用于詢問用于連接服務(wù)器的IP地址和TLS配置猩谊。
Choosing between application and network interceptors
每個攔截器都有自己的長處:
應(yīng)用攔截器
- 不必擔心中間的response像重定向和重試
- 只會被調(diào)用一次,包括從緩存取出的response
- 觀察應(yīng)用的最初意圖祭刚,不關(guān)心OkHttp注入的類似<code>If-None-Match</code>頭牌捷。
- 允許短路并且不調(diào)用<code>Chain.proceed()</code>
- 允許重試并且重復調(diào)用<code>Chain.proceed()</code>
網(wǎng)絡(luò)攔截器
- 能夠操作中間的response像重定向和重試
- 緩存的response將短路網(wǎng)絡(luò),此時不掉用攔截器
- 觀察整個網(wǎng)絡(luò)傳輸?shù)臄?shù)據(jù)
- 訪問帶有request的<code>Connection</code>
Rewriting Requests
攔截器可以添加涡驮,刪除或替換請求頭暗甥,也可以轉(zhuǎn)換那些包含體的請求。例如你可以在服務(wù)器支持的情況下使用應(yīng)用攔截器壓縮請求體捉捅。
/** This interceptor compresses the HTTP request body. Many Webservers can't handle this! */
final class GzipRequestInterceptor implements Interceptor {
@Override public Response interceptor(Interceptor.Chain chain) thorws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding")) {
return chain.proceed(originalRequest);
}
Request comressedRequest = 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 adcance!
}
@Override public void wirteTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
Rewriting Responses
對應(yīng)的撤防,攔截器可以重寫響應(yīng)頭,轉(zhuǎn)換響應(yīng)體棒口。一般來說這比重寫請求頭危險的因為這可能改變了服務(wù)器的意愿寄月。
如果你有一個棘手的情況必須處理結(jié)果辜膝,重寫響應(yīng)頭是解決問題的有力方法。例如你可以通過修復服務(wù)器丟失的<code>Cache-Control</code>響應(yīng)頭來保證更好的response緩存漾肮。
/** 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ù)器完成對應(yīng)的補充這中方式最有效厂抖。
Availability
OkHttp的攔截器需要版本在2.2以上,不幸的是攔截器對<code>OkUrlFactory</code>無效初橘。有些庫構(gòu)建在OkHttp之上包括Retrofit ≤ 1.8 和 Picasso ≤ 2.4验游。