OKhttp3 源碼解析(二)
OkHttpClient (大管家)的配置參數解析
這一期來一一解讀,OkHttpClient 中的 參數對象是幹什麼的
- Dispatcher (調度器) :負責控制 最大請數‘64’ 和 單服務器 最多連接數‘5’
- connectionPool (連接池):類似於 線程池,當有 ‘連接’處於空閒狀態,就不創建新的資源了,
-
interceptors (攔截器):在指定的請求階段 進行攔截,可以自定義 interceptors
-
networkInterceptors
-
eventListenerFactory(對請求過程中的每個階段,進行監聽記錄的工廠)
-
retryOnConnectionFailure(連接失敗重試):包括請求失敗、連接失敗。
-
authenticator (驗證身份):在發請求的時候 驗證 token 之類
身份驗證過期了 重新請求
```kotlin
val client = OkHttpClient()
client.newBuilder().authenticator(object:Authenticator{
override fun authenticate(route: Route?, response: Response): Request? {
return response.request.newBuilder()
.header("Authorization","Bearer asdasdqqeweretewrt")
.build()
}
})
```
-
followRedirects (重定向) 默認是開啓的
-
followSslRedirects (https 重定向協議切換) 默認是開啓的
* 比如 從一個 http 網站 重定向到一個https 網站
10. cookieJar (存放cookjar的罐子)
11. cache
12. dns (通過域名解析 ip 地址)
```KOT
${InetAddress.getAllByName("www.baidu.com")[0]}")
```
- Proxy(代理) 如果 代理就用他配置
```kotlin
public enum Type {
/**
* Represents a direct connection, or the absence of a proxy.
*/
DIRECT, (直連)
/**
* Represents proxy for high level protocols such as HTTP or FTP.
*/
HTTP,
/**
* Represents a SOCKS (V4 or V5) proxy.
*/
SOCKS
};
```
-
proxyAuthenticator (代理的授權身份驗證)
-
socketFactory
-
sslSocketFactory
-
x509TrustManager (證書Manager)
-
connectionSpecs (連接規則):加密算法、TLS 版本 ()
-
protocols (支持的那些協議 ):http 的版本號
-
hostnameVerifier (主機名驗證)
-
certificatePinner (可以額外增加一個 證書驗證)
> 可以增加一點 安全性 (但是最好別用,但是換證書就有問題)
```kotlin
val certificatePinner = CertificatePinner.Builder()
.add("hostname","sha256/aaaaaaaaaaaaaaa")
.build()
val client = OkHttpClient()
client.newBuilder()
.certificatePinner(certificatePinner)
.authenticator(object:Authenticator{
override fun authenticate(route: Route?, response: Response): Request? {
return response.request.newBuilder()
.header("Authorization","Bearer asdasdqqeweretewrt")
.build()
}
})
```
- pingIntervalMillis (心跳間隔時間配置):http 2 、socket 使用
)
}
})
```
- pingIntervalMillis (心跳間隔時間配置):http 2 、socket 使用