OKhttp3 源碼解析(二)OkHttpClient 大管家

OKhttp3 源碼解析(二)

OkHttpClient (大管家)的配置參數解析

這一期來一一解讀,OkHttpClient 中的 參數對象是幹什麼的

  1. Dispatcher (調度器) :負責控制 最大請數‘64’ 和 單服務器 最多連接數‘5’
  2. connectionPool (連接池):類似於 線程池,當有 ‘連接’處於空閒狀態,就不創建新的資源了,

在這裏插入圖片描述

  1. interceptors (攔截器):在指定的請求階段 進行攔截,可以自定義 interceptors

  2. networkInterceptors

  3. eventListenerFactory(對請求過程中的每個階段,進行監聽記錄的工廠)

  4. retryOnConnectionFailure(連接失敗重試):包括請求失敗、連接失敗。

  5. 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()
              }
          })
  ```
  1. followRedirects (重定向) 默認是開啓的

  2. followSslRedirects (https 重定向協議切換) 默認是開啓的

  * 比如 從一個 http 網站 重定向到一個https 網站

10.  cookieJar (存放cookjar的罐子)

11.  cache

12.  dns (通過域名解析 ip 地址) 

    ```KOT
    ${InetAddress.getAllByName("www.baidu.com")[0]}")
    ```
  1. 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
    };
```
  1. proxyAuthenticator (代理的授權身份驗證)

  2. socketFactory

  3. sslSocketFactory

  4. x509TrustManager (證書Manager)

  5. connectionSpecs (連接規則):加密算法、TLS 版本 ()

  6. protocols (支持的那些協議 ):http 的版本號

  7. hostnameVerifier (主機名驗證)

  8. 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()
            }
        })
```
  1. pingIntervalMillis (心跳間隔時間配置):http 2 、socket 使用

)
}
})
```

  1. pingIntervalMillis (心跳間隔時間配置):http 2 、socket 使用
瞭解了以上 配置參數解析 ,是不是感覺 OKhttp 和 Http 是密切相關的了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章