OKHTTP異步和同步請(qǐng)求簡(jiǎn)單分析
OKHTTP攔截器緩存策略CacheInterceptor的簡(jiǎn)單分析
OKHTTP攔截器ConnectInterceptor的簡(jiǎn)單分析
OKHTTP攔截器CallServerInterceptor的簡(jiǎn)單分析
OKHTTP攔截器BridgeInterceptor的簡(jiǎn)單分析
OKHTTP攔截器RetryAndFollowUpInterceptor的簡(jiǎn)單分析
OKHTTP結(jié)合官網(wǎng)示例分析兩種自定義攔截器的區(qū)別
在了解自定義攔截器之前胯陋,先來(lái)看一下 OKHTTP
官網(wǎng)提供的示例代碼塊袱箱,LoggingInterceptor
是用于在網(wǎng)絡(luò)請(qǐng)求期間的日志記錄攔截器。
1盟萨、LoggingInterceptor示例代碼
通過(guò)下面的代碼可以看出捻激,它就是用于在請(qǐng)求發(fā)送前
和網(wǎng)絡(luò)響應(yīng)后
的打印日志信息的攔截器。
在 LoggingInterceptor
中主要做了 3 件事:
- 1.請(qǐng)求前-打印請(qǐng)求信息垃杖;
- 2.網(wǎng)絡(luò)請(qǐng)求-遞歸去調(diào)用其他攔截器發(fā)生網(wǎng)絡(luò)請(qǐng)求丈屹;
- 3.網(wǎng)絡(luò)響應(yīng)后-打印響應(yīng)信息;
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
//1.請(qǐng)求前--打印請(qǐng)求信息
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
//2.網(wǎng)絡(luò)請(qǐng)求
Response response = chain.proceed(request);
//3.網(wǎng)絡(luò)響應(yīng)后--打印響應(yīng)信息
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;
}
}
2彩库、Application Intercetor和NetworkInterceptor的區(qū)別
2.1 攔截器調(diào)用流程
在官方文檔中OKHTTP官網(wǎng)示例用 LoggingInterceptor
作為示例骇钦,解釋了 Application Intercetor
和 NetworkInterceptor
的區(qū)別竞漾。
在看兩種攔截器的區(qū)別之前,還是要點(diǎn)擊上面的鏈接去看看坦仍,之后再看這個(gè)博客的總結(jié)會(huì)好點(diǎn)叨襟。到這里糊闽,默認(rèn)就是已經(jīng)看過(guò)了官網(wǎng)的示例了,那我們就使用一個(gè)圖來(lái)看看攔截器的調(diào)用過(guò)程:
從上面的調(diào)用關(guān)系可以看出除了紅色圈出的攔截器之外都是系統(tǒng)提供的攔截器提澎,這整個(gè)過(guò)程是遞歸的執(zhí)行過(guò)程盼忌,在
CallServerInterceptor
中得到最終的Response
之后,將response
按遞歸逐級(jí)進(jìn)行返回看成,期間會(huì)經(jīng)過(guò)NetworkInterceptor
最后到達(dá)Application Interceptor
跨嘉。
2.1 給網(wǎng)絡(luò)請(qǐng)求添加攔截器
- 添加 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();
響應(yīng)數(shù)據(jù):
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
- 添加 NetworkInterceptor
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();
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)給出的
NetworkInterceptor
和Application Interceptor
的區(qū)別在上面的圖中就可以看出:
-
Application Interceptor
是第一個(gè)Interceptor
因此它會(huì)被第一個(gè)執(zhí)行梦重,因此這里的 request 還是最原始的亮瓷。而對(duì)于response
而言呢,因?yàn)檎麄€(gè)過(guò)程是遞歸的調(diào)用過(guò)程蚓胸,因此它會(huì)在CallServerInterceptor
執(zhí)行完畢之后才會(huì)將Response
進(jìn)行返回斗塘,因此在Application Interceptor
這里得到的response
就是最終的響應(yīng)馍盟,雖然中間有重定向,但是這里只關(guān)心最終的response
八毯。
-
NetwrokInterceptor
處于第 6 個(gè)攔截器中瞄桨,它會(huì)經(jīng)過(guò)RetryAndFollowIntercptor
進(jìn)行重定向并且也會(huì)通過(guò)BridgeInterceptor
進(jìn)行request
請(qǐng)求頭和 響應(yīng)resposne
的處理芯侥,因此這里可以得到的是更多的信息。在打印結(jié)果可以看到它內(nèi)部是發(fā)生了一次重定向操作廓俭,在上圖可以看出唉工,為什么NetworkInterceptor
可以比Application Interceptor
得到更多的信息了淋硝。
Application Interceptor 適用于在請(qǐng)求前統(tǒng)一添加一些公共參數(shù)宽菜,例如在添加 APP 的版本號(hào)竿报,用戶 ID ,手機(jī)版本號(hào)仰楚,運(yùn)營(yíng)商類型等參數(shù)犬庇。或者對(duì)響應(yīng)體的數(shù)據(jù)進(jìn)行 json 轉(zhuǎn)化等操作捂襟。
NetwrokInterceptor 在這一層攔截器中可以獲取到最終發(fā)送請(qǐng)求的 request 欢峰,也可以獲取到真正發(fā)生網(wǎng)絡(luò)請(qǐng)求回來(lái)的 response 響應(yīng),從而修改對(duì)應(yīng)的請(qǐng)求或者響應(yīng)數(shù)據(jù)宠漩。
3懊直、兩種攔截器的區(qū)別
下面是官網(wǎng)給出的區(qū)別室囊,根據(jù)我自己的理解,使用中文標(biāo)出了自己的解釋盼铁。
Application interceptors
- Don't need to worry about intermediate responses like redirects and retries.
不需要去關(guān)心中發(fā)生的重定向和重試操作尝偎。因?yàn)樗幱诘谝粋€(gè)攔截器,會(huì)獲取到最終的響應(yīng) response 肤寝。 - Are always invoked once, even if the HTTP response is served from the cache.
只會(huì)被調(diào)用一次急前,即使這個(gè)響應(yīng)是從緩存中獲取的裆针。 - Observe the application's original intent. Unconcerned with -OkHttp-injected headers like If-None-Match.
只關(guān)注最原始的請(qǐng)求寺晌,不去關(guān)系請(qǐng)求的資源是否發(fā)生了改變澡刹,我只關(guān)注最后的 response 結(jié)果而已罢浇。 - Permitted to short-circuit and not call Chain.proceed().
因?yàn)槭堑谝粋€(gè)被執(zhí)行的攔截器,因此它有權(quán)決定了是否要調(diào)用其他攔截攒岛,也就是 Chain.proceed() 方法是否要被執(zhí)行胞锰。 - Permitted to retry and make multiple calls to Chain.proceed()
因?yàn)槭堑谝粋€(gè)被執(zhí)行的攔截器嗅榕,因此它有可以多次調(diào)用 Chain.proceed() 方法,其實(shí)也就是相當(dāng)與重新請(qǐng)求的作用了兼雄。
Network Interceptors
Able to operate on intermediate responses like redirects and retries.
因?yàn)?NetworkInterceptor 是排在第 6 個(gè)攔截器中帽蝶,因此可以操作經(jīng)過(guò) RetryAndFollowup 進(jìn)行失敗重試或者重定向之后得到的resposne。Not invoked for cached responses that short-circuit the network.
對(duì)于從緩存獲取的 response 則不會(huì)去觸發(fā) NetworkInterceptor 金砍。因?yàn)轫憫?yīng)直接從 CacheInterceptor 返回了麦锯。Observe the data just as it will be transmitted over the network.
觀察數(shù)據(jù)在網(wǎng)絡(luò)中的傳輸扶欣。Access to the Connection that carries the request.
可以獲得裝載請(qǐng)求的連接。