在Okhttp3中攔截器分為應用攔截器和網(wǎng)絡攔截器,兩者有很大的區(qū)別,在使用時一定要注意防止用錯造成不必要的麻煩,接下來我將說明這兩個攔截器的差異.
-
首先看看Okhttp執(zhí)行流程圖
攔截器執(zhí)行過程 -
再看攔截器執(zhí)行順序圖
根據(jù)上面的兩張圖,我們可以列出Application Interceptor和Network Interceptor的執(zhí)行流程圖

流程圖.png
Application interceptors
- Don't need to worry about intermediate responses like redirects and retries.
不需要關心是否重定向或者失敗重連 - Are always invoked once, even if the HTTP response is served from the cache.
應用攔截器只會調(diào)用一次,即使數(shù)據(jù)來源于緩存 - Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
只考慮應用的初始意圖,不去考慮Okhhtp注入的Header比如:if-None-Match,意思就是不管其他外在因素只考慮最終的返回結(jié)果 - Permitted to short-circuit and not call Chain.proceed().
根據(jù)第二張圖我們可以看出,自定義的應用攔截器是第一個開始執(zhí)行的攔截器,所以這句話的意思就是,應用攔截器可以決定是否執(zhí)行其他的攔截器,通過Chain.proceed(). - Permitted to retry and make multiple calls to Chain.proceed().
和上一句的意思差不多,可以執(zhí)行多次調(diào)用其他攔截器,通過Chain.proceed().
Network Interceptors
- Able to operate on intermediate responses like redirects and retries.
根據(jù)第三張圖,我們可以理解這句話的意思是,網(wǎng)絡攔截器可以操作重定向和失敗重連的返回值 - Not invoked for cached responses that short-circuit the network.
根據(jù)第一張圖,我們可以以看出,這句換的意思是,取緩存中的數(shù)據(jù)就不會去還行Chain.proceed().所以就不能執(zhí)行網(wǎng)絡攔截器 - Observe the data just as it will be transmitted over the network.
意思是通過網(wǎng)絡攔截器可以觀察到所有通過網(wǎng)絡傳輸?shù)臄?shù)據(jù) - Access to the Connection that carries the request.
根據(jù)第二張圖我們可以看出,請求服務連接的攔截器先于網(wǎng)絡攔截器執(zhí)行,所以在進行網(wǎng)絡攔截器執(zhí)行時,就可以看到Request中服務器請求連接信息,因為應用攔截器是獲取不到對應的連接信息的。

