Interceptors##
攔截器(Interceptors)是一種強有力的途徑,來監控,改寫和重試HTTP訪問。下面是一個簡單的攔截器,對流出的請求和流入的響應記錄日志。
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(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)
的一次調用時是關鍵的一步。這個看起來簡單的方法是HTTP工作實際發生的地方,產生一個滿足請求的響應。
多個攔截器可以鏈接起來。假如說你有一個壓縮攔截器和一個求和校驗攔截器:你將需要決定數據是先壓縮然后求和校驗,或者先求和校驗再壓縮。OkHttp使用列表來追蹤攔截器,多個攔截器是被有序的調用。

Application Interceptors###
攔截器被注冊為應用(application)攔截器或者網絡(network)攔截器。我們將用上面定義的LoggingInterceptor
來展示這兩者的區別。
要注冊應用攔截器,在OkHttpClient.interceptors()
方法返回的列表上調用add()
方法:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
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會自動跟隨這一重定向。我們的應用攔截器會被調用一次,方法chain.proceed()
返回的響應是重定向后的響應:
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
我們可以通過response.request().url()
同request.url()
不同看出訪問被重定向。這兩個日志語句記錄了兩個不同了URL。
Network Interceptors###
注冊網絡攔截器的方法很類似。添加攔截器到networkInterceptors()
列表,取代interceptors()
列表:
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new LoggingInterceptor());
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();
當我們運行這一段代碼時,攔截器執行了兩次。一次是初始的到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
上面的網絡請求也包含更多的數據,例如由OkHttp添加的請求頭Accept-Encoding: gzip
,通知支持對響應的壓縮。網絡攔截器鏈有一個非空的連接,用來詢問我們連接web服務器使用的IP地址和TLS配置。
選擇應用攔截器還是網絡攔截器###
兩個攔截器鏈有自身的相對優勢。
Application Interceptors
- 不用擔心中間過程的響應,例如重定向和重試。
- 始終調用一次,即使HTTP響應來自於緩存。
- 觀察應用原始的意圖。不用關注由OkHttp注入的頭信息,例如
If-None-Match
。 - 允許短路,不調用
Chain.proceed()
。 - 允許重試,多次調用
Chain.proceed()
。
Network Interceptors
- 能操作中間響應,例如重定向和重試。
- 發生網絡短路的緩存響應時,不被調用。
- 觀察將通過網絡傳輸的數據。
- 可以獲取到攜帶請求的
connection
。
改寫請求###
攔截器可以添加,移除或者替換請求頭。它們也可以改變請求體。例如,如果你連接的web服務器支持,你可以用一個應用攔截器來壓縮請求體。
/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
final class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(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();
}
};
}
}
改寫響應###
對應的,攔截器也可以改寫響應頭和改變響應體。這通常來講比改寫請求頭更危險,因為它可能違背了web服務器的預期。
如果你在一個微妙的情境下,並准備好去處理對應的后果,改寫響應頭是一種有力的方式來解決問題。例如,你可以修復服務器錯誤配置的緩存控制響應頭,來優化對響應的緩存。
/** Dangerous interceptor that rewrites the server's cache-control header. */
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.header("Cache-Control", "max-age=60")
.build();
}
};
通常來講,這種方式在補充相應的服務器問題修復時最有用。
可用性###
OkHttp攔截器需要2.2版本以上。不幸的是,攔截器對OkUrlFactory
,和任何依賴OkUrlFactory
的庫無效,包含Retrofit 1.8以下和Picasso 2.4版本以下。