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 是密切相关的了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章