攔截器(Interceptor)是一個強大的工具,(在上邊的我翻譯的retrofit教程中列出了如何使用攔截器為請求添加認(rèn)證token,假如token過期刷新token的文章我還沒寫,有興趣的同學(xué)可以留言)他可以監(jiān)視,重寫,重試你的call,下面是一個簡單的例子,自定義了一個攔截器實現(xiàn)了發(fā)出的請求和接收的響應(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;
}
}
對chain.proceed(request)的調(diào)用是攔截器實現(xiàn)的關(guān)鍵部分。
攔截器可以鏈接。假設(shè)你有一個壓縮攔截器和一個檢查結(jié)果攔截器,你需要決定攔截器調(diào)用的順序。OkHttp使用列表方式來跟蹤攔截器,攔截器會按你的編寫順序調(diào)用。

程序攔截器
攔截器分為程序攔截器和網(wǎng)絡(luò)攔截器。來看看上面定義的LoggingInterceptor來顯示兩者的差異。
通過在OkHttpClient.Builder上調(diào)用addInterceptor()來注冊應(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();
網(wǎng)址http://www.publicobject.com/helloworld.txt重定向到https://publicobject.com/helloworld.txt,OkHttp會自動跟蹤此重定向。 我們的應(yīng)用程序攔截器被調(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
我們可以看到發(fā)出請求后被重定向,因為response.request().url不同于request.url。這兩個日志語句記錄了兩個不同的URL。
網(wǎng)絡(luò)攔截器
注冊網(wǎng)絡(luò)攔截器和注冊程勛攔截器非常相似。用addNetworkInterceptor()方法代替addInterceptor()方法即可:
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();
當(dāng)我們運行上述代碼時,攔截器會執(zhí)行兩次。一次是在請求網(wǎng)址http://www.publicobject.com/helloworld.txt的時候,一次是在被重定向到https://publicobject.com/helloworld.txt的時候。日志如下
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添加的Accept-Encoding:gzip頭,以宣告對響應(yīng)壓縮的支持。 網(wǎng)絡(luò)攔截器的Chain有一個非空連接,可用于查詢用于連接到Web服務(wù)器的IP地址和TLS配置。
使用程序攔截器還是網(wǎng)絡(luò)攔截器
每個攔截器的優(yōu)點是相對的:
程序攔截器
- 不需要擔(dān)心中間響應(yīng)(如重定向和重試)
- 只調(diào)用一次,即使HTTP響應(yīng)是從緩存讀取的
- 遵守應(yīng)用程序原始的意圖,不關(guān)心OkHttp注入的頭信息,例如If-None-Match
- 允許短路,不調(diào)用Chain.proceed()
- 允許重試并對多個Chain.proceed()調(diào)用
網(wǎng)路攔截器
- 能夠?qū)χ虚g響應(yīng)(如重定向和重試)進(jìn)行操作。
- 不調(diào)用緩存響應(yīng)使網(wǎng)絡(luò)短路。
- 觀察數(shù)據(jù),就像它將通過網(wǎng)絡(luò)傳輸一樣。
- 能夠訪問攜帶請求的連接。
重寫請求
攔截器能夠增加、移除或者替換請求的頭信息,也可以轉(zhuǎn)換請求體。例如,假如你正在請求一個支持壓縮的網(wǎng)站,你可以使用程序攔截器來添加一個請求體壓縮。
/** 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)體,但是這樣通常比重寫請求頭更危險,因為它可能違反網(wǎng)絡(luò)協(xié)議。
如果你正處在一個棘手的情況,并準(zhǔn)備處理可能發(fā)生的后果,重寫響應(yīng)頭是解決問題的辦法。例如,你可以秀谷服務(wù)器配置錯的的緩存控制響應(yīng)頭譯啟用更好的響應(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();
}
};
通常,這種方法在補充Web服務(wù)器上的相應(yīng)修復(fù)時效果最好!
可用性
OkHttp的攔截器需要OkHttp 2.2或更高版本。攔截器不能使用OkUrlFactory或構(gòu)建它的庫,包括Retrofit≤1.8和Picasso≤2.4。