Interceptor OkHttp
Interceptor可以說是OkHttp的核心功能郎汪,它就是通過Interceptor來完成監(jiān)控管理嚼蚀、重寫和重試請求的翩伪。下面是一個簡單的Interceptor轰枝,可以監(jiān)控request的輸入?yún)?shù)和response的輸出內容拧簸。
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)
,每個Interceptor實現(xiàn)里都有這個調用方法燕少,這個看起來簡單的方法卻是所有的HTTP請求卡者、生成response的關鍵所在。
Interceptors可以被串聯(lián)起來(chained)客们。OkHttp使用lists來管理Interceptors,讓這些Interceptors按順序被調用崇决。
Application Interceptors
我們只能通過Application Interceptors或者Network Interceptors來注冊自定義的Interceptors,其他Interceptors都是OkHttp幫你做好了的底挫,比如RetryAndFollowUpInterceptor恒傻、BridgeInterceptor、CacheInterceptor凄敢、ConnectInterceptor碌冶、CallServerInterceptor。這里的OkHttp會啟動一個攔截器調用鏈涝缝,攔截器遞歸調用之后最后返回請求的響應Response扑庞。這里的攔截器分層的思想就是借鑒的網(wǎng)絡里的分層模型的思想。請求從最上面一層到最下一層拒逮,響應從最下一層到最上一層罐氨,每一層只負責自己的任務,對請求或響應做自己負責的那塊的修改滩援。
Application Interceptors和Network Interceptors分別位于七層模型的第一層和第六層栅隐。這個從RealCall
里的getResponseWithInterceptorChain
方法中就可以看出來:
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors()); // Application Interceptors
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors()); // Network Interceptors
}
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
我們通過這個LoggingInterceptor
來說明Application Interceptors和Network Interceptors的區(qū)別。
通過OkHttpClient.Builder
的addInterceptor()
注冊一個 application interceptor:
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 http://www.publicobject.com/helloworld.txt
會重定向到https://publicobject.com/helloworld.txt
,OkHttp會自動follow這次重定向玩徊。application interceptor會被調用once租悄,并且會返回攜帶有重定向后的redirected 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
我們可以看到恩袱,會重定向是因我request的URL和response的URL是不同的泣棋,日志也打印了兩個不同的URLs。
Network Interceptors
注冊一個Network Interceptors的方式是非常類似的畔塔,只需要將addInterceptor()
替換為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();
當我們執(zhí)行上面這段代碼潭辈,這個interceptor會執(zhí)行twice。一次是調用在初始的request http://www.publicobject.com/helloworld.txt
澈吨,另外一次是調用在重定向后的redirect request 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
Application and Network interceptors 該如何選擇
這兩個interceptor都有他們各自的優(yōu)缺點:
Application Interceptors
- 不需要關心由重定向、重試請求等造成的中間response產(chǎn)物谅辣。
- 總會被調用一次修赞,即使HTTP response是從緩存(cache)中獲取到的。
- 關注原始的request桑阶,而不關心注入的headers榔组,比如
If-None-Match
熙尉。 - interceptor可以被取消調用,不調用
Chain.proceed()
搓扯。 - interceptor可以重試和多次調用
Chain.proceed()
。
Network Interceptors
- 可以操作由重定向包归、重試請求等造成的中間response產(chǎn)物锨推。
- 如果是從緩存中獲取cached responses ,導致中斷了network公壤,是不會調用這個interceptor的换可。
- 數(shù)據(jù)在整個network過程中都可以通過Network Interceptors監(jiān)聽。
- 可以獲取攜帶了request的
Connection
厦幅。
使用Interceptor的說明
在OkHttp 2.2版本才加入了Interceptor功能沾鳄,而且,Interceptor不能使用OkUrlFactory
确憨,或者是基于OkHttp的低版本第三方庫译荞,比如Retrofit ≤ 1.8 and Picasso ≤ 2.4 。