原文:https://www.songma.com/news/txtlist_i28215v.html
使用
1、okhttp工作的大致流程
1.1、整體流程
(1)、當我們通過OkhttpClient創立一個okHttpClient 、Request 、Call,並發起同步或者異步請求時;
(2)、okhttp會通過Dispatcher對我們所有的Call(RealCall實現類)進行統一管理,並通過execute()及enqueue()方法對同步或者異步請求進行執行;
(3)、execute()及enqueue()這兩個方法會最終調用RealCall中的getResponseWithInterceptorChain()方法,從阻攔器鏈中獲取返回結果;
(4)、攔截器鏈中,依次通過ApplicationInterceptor(應用攔截器)、RetryAndFollowUpInterceptor(重定向阻攔器)、BridgeInterceptor(橋接阻攔器)、CacheInterceptor(緩存阻攔器)、ConnectInterceptor(連接阻攔器)、NetwrokInterceptor(網絡攔截器)、CallServerInterceptor(請求阻攔器)對請求依次處理,與服務的建立連接后,獲取返回數據,再經過上述阻攔器依次解決后,最后將結果返回給調用方。
提供兩張圖便於了解和記憶:
okhttp整體流程1
okhttp整體流程2
1.2、各大阻攔器
getResponseWithInterceptorChain方法,也是整個OkHttp實現責任鏈模式的核心。
#RealCall
fun getResponseWithInterceptorChain(): Response {
//創建攔截器數組
val interceptors = mutableListOf<Interceptor>()
//添加應用攔截器
interceptors += client.interceptors
//添加重試和重定向攔截器
interceptors += RetryAndFollowUpInterceptor(client)
//添加橋接攔截器
interceptors += BridgeInterceptor(client.cookieJar)
//添加緩存攔截器
interceptors += CacheInterceptor(client.cache)
//添加連接攔截器
interceptors += ConnectInterceptor
if (!forWebSocket) {
//添加網絡攔截器
interceptors += client.networkInterceptors
}
//添加請求攔截器
interceptors += CallServerInterceptor(forWebSocket)
//創建責任鏈
val chain = RealInterceptorChain(interceptors, transmitter, null, 0, originalRequest, this,
client.connectTimeoutMillis, client.readTimeoutMillis, client.writeTimeoutMillis)
...
try {
//啟動責任鏈
val response = chain.proceed(originalRequest)
...
return response
} catch (e: IOException) {
...
}
}
攔截器作用:
ApplicationInterceptor: 應用攔截器,通過addInterceptor添加,拿到的是原始請求,可以添加一些自定義header、通用參數、參數加密、網關接入等等。
RetryAndFollowUpInterceptor:重試和重定向攔截器,處理錯誤重試和重定向
BridgeInterceptor:橋接攔截器,主要工作是為請求添加cookie、添加固定的header,比如Host、Content-Length、Content-Type、User-Agent等等,然后保存響應結果的cookie,如果響應使用gzip壓縮過,則還需要進行解壓。
CacheInterceptor:緩存攔截器,如果命中緩存則不會發起網絡請求。
ConnectInterceptor:連接攔截器,內部會維護一個連接池,負責連接復用、創建連接(三次握手等等)、釋放連接以及創建連接上的socket流。
NetworkInterceptors:網絡攔截器,用戶自定義,通常用於監控網絡層的數據傳輸。
CallServerInterceptor:網絡請求攔截器,在前置准備工作完成后,真正發起了網絡請求。
至此,OkHttp的核心執行流程就結束了,是不是有種豁然開朗的感覺?