攔截器是一個非常強大的機制,可以監視,重寫和重試call。這里是一個簡單的攔截器,用來打印出去的請求和收到的響應。
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)是每個攔截器實現的一個主要部分。這個簡單的方法是HTTP工作發生,產出滿足請求的響應之處,
攔截器可以鏈接。假如有一個壓縮攔截器和一個檢驗和攔截器:你需要決定是先數據進行壓縮然后檢驗和,還是先檢驗和然后進行壓縮。OkHttp使用列表來跟蹤攔截器,并且攔截器按順序被調用。
應用攔截器
攔截器可以注冊為應用攔截器和網絡攔截器。我們使用上面定義的LoggingInterceptor來展示它們的不同。
通過在OkHttpCleint.Builder上調用addInterceptor()來注冊一個應用攔截器:
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();
http://www.publicobject.com/helloworld.txt這個URL重定向到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
我看可以看到我們已經重定向了,引文reponse.request().url()與request.url()不同。兩個日志語句打印了兩個不同的URL。
網絡攔截器
注冊一個網絡攔截器很相似。調用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();
當我們運行這個代碼,攔截器會執行兩次。一次是訪問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頭來通知支持響應壓縮。網絡攔截器的Chain有一個非空Connection,可以用來訪問IP地址和用來連接網絡服務器的TLS配置。
選擇應用攔截器還是網絡攔截器?
每種攔截器chain有相對的優勢。
-
應用攔截器
- 不需要關心像重定向和重試這樣的中間響應。
- 總是調用一次,即使HTTP響應從緩存中獲取服務。
- 監視應用原始意圖。不關心OkHttp注入的像If-None-Match頭。
- 允許短路并不調用Chain.proceed()。
- 允許重試并執行多個Chain.proceed()調用。
-
網絡攔截器
- 可以操作像重定向和重試這樣的中間響應。
- 對于短路網絡的緩存響應不會調用。
- 監視即將要通過網絡傳輸的數據。
- 訪問運輸請求的Connection。
重寫請求
攔截器可以添加,移除或替換請求頭。如果有請求主體,它們也可以改變。例如,如果你連接一個已知支持請求主體壓縮的網絡服務器,你可以使用一個應用攔截器來添加請求主體壓縮。
/** 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();
}
};
}
}
重寫響應
對稱地,攔截器可以重寫響應頭并且改變響應主體。這個通常是比重寫請求頭更危險的,因為它可能違背網絡服務器的期望!
如果你在一個棘手的環境下并準備處理結果,重寫響應頭是一個強大的方式來解決問題。例如,你可以修復一個服務器未配置的Cache-Control響應頭來啟用響應緩存:
/** 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();
}
};
通常當在網絡服務器上完成相應的修復時,這種方式會更好的工作。
可用性
OkHttp的攔截器需要OkHttp2.2或更高。不幸地,攔截器無法與OkUrlFactory一起工作,或者基于它構建的庫,包括等于低于1.0版本的Retrofit以及等于低于2.4版本的Picasso。
原文鏈接:
https://github.com/square/okhttp/wiki/Interceptors
OkHttp官方文檔系列文章: