读OkHttp3源码(一):OkHttpClient

本文主要探讨OkHttp3中的OkHttpClient组件,它是HTTP请求的工厂,利用响应缓存、线程池等功能优化请求。通过默认构造函数或Builder可创建实例,自定义配置。文章详细介绍了OkHttpClient的构造方法,包括Builder中涉及的调度器、代理、协议、拦截器等关键参数的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,简介:OkHttpClient是Call的的工厂,可用于发送HTTP请求并读取其响应。 大多数应用程序可以对所有HTTP请求使用一个OkHttpClient,这得益于共享的响应缓存线程池连接重用等等。

  • 要使用默认设置创建OkHttpClient,请使用默认构造函数。
  • 或者使用OkHttpClient.Builder创建自定义配置的实例。
  • 要在发出请求之前调整现有客户端,请使用newBuilder()。

2,构造方法:

public OkHttpClient() {
    this(new Builder());
}

默认构造方法调用另外一个私有构造方法,需要传入一个Builder对象:

private OkHttpClient(Builder builder) {
        this.dispatcher = builder.dispatcher;
        this.proxy = builder.proxy;
        this.protocols = builder.protocols;
        this.connectionSpecs = builder.connectionSpecs;
        this.interceptors = Util.immutableList(builder.interceptors);
        this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
        this.proxySelector = builder.proxySelector;
        this.cookieJar = builder.cookieJar;
        this.cache = builder.cache;
        this.internalCache = builder.internalCache;
        this.socketFactory = builder.socketFactory;

        boolean isTLS = false;
        for (ConnectionSpec spec : connectionSpecs) {
            isTLS = isTLS || spec.isTls();
        }

        if (builder.sslSocketFactory != null || !isTLS) {
            this.sslSocketFactory = builder.sslSocketFactory;
        } else {
            try {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, null, null);
                this.sslSocketFactory = sslContext.getSocketFactory();
            } catch (GeneralSecurityException e) {
                //系统没有TLS。就放弃。
                throw new AssertionError();
            }
        }
        if (sslSocketFactory != null && builder.trustRootIndex == null) {
            X509TrustManager trustManager = Platform.get().trustManager(sslSocketFactory);
            if (trustManager == null) {
                throw new IllegalStateException("Unable to extract the trust manager on " + Platform.get()
                        + ", sslSocketFactory is " + sslSocketFactory.getClass());
            }
            this.trustRootIndex = Platform.get().trustRootIndex(trustManager);
            this.certificatePinner = builder.certificatePinner.newBuilder()
                    .trustRootIndex(trustRootIndex)
                    .build();
        } else {
            this.trustRootIndex = builder.trustRootIndex;
            this.certificatePinner = builder.certificatePinner;
        }
        this.hostnameVerifier = builder.hostnameVerifier;
        this.proxyAuthenticator = builder.proxyAuthenticator;
        this.authenticator = builder.authenticator;
        this.connectionPool = builder.connectionPool;
        this.dns = builder.dns;
        this.followSslRedirects = builder.followSslRedirects;
        this.followRedirects = builder.followRedirects;
        this.retryOnConnectionFailure = builder.retryOnConnectionFailure;
        this.connectTimeout = builder.connectTimeout;
        this.readTimeout = builder.readTimeout;
        this.writeTimeout = builder.writeTimeout;
    }

通过builder对象默认的属性对OkHttpClient里的dispatcher(调度器)、proxy(代理)、protocols(支持协议)、connectionSpecs(连接策略)、interceptors(拦截器)、networkInterceptors(网络拦截器)、proxySelector(代理选择器)、cookieJar(cookie存储)、cache(缓存)、internalCache(okHttp自己使用的缓存,不对外)、socketFactory(套接字工厂)、sslSocketFactory(ssl套接字工厂)、trustRootIndex(可信赖根)、hostnameVerifier(主机名称校验器)、certificatePinner(固定证书)、proxyAuthenticator(代理服务器授权验证)

 

/**
 * 请求(calls)的的工厂类,可用于发送HTTP请求并读取其响应。
 * 大多数应用程序可以对所有HTTP请求使用一个OkHttpClient,这得益于共享的响应缓存、线程池、连接重用等等。
 * 要使用默认设置创建OkHttpClient,请使用默认构造函数。或者使用OkHttpClient.Builder创建自定义配置的实例。
 * 要在发出请求之前调整现有客户端,请使用newBuilder()。
 * 这个例子显示了一个超时30秒的调用:
 * <pre>
 *     OkHttpClient client = ...
 *     OkHttpClient clientWith30sTimeout = client.newBuilder()
 *          .readTimeout(30, TimeUnit.SECONDS)
 *          .build();
 *    Response response = clientWith30sTimeout.newCall(request).execute();
 * </pre>
 */
public class OkHttpClient implements Cloneable, Call.Factory {
    private static final List<Protocol> DEFAULT_PROTOCOLS = Util.immutableList(
            Protocol.HTTP_2, Protocol.SPDY_3, Protocol.HTTP_1_1);

    private static final List<ConnectionSpec> DEFAULT_CONNECTION_SPECS = Util.immutableList(
            ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT);

    static {
        Internal.instance = new Internal() {
            @Override
            public void addLenient(Headers.Builder builder, String line) {
                builder.addLenient(line);
            }

            @Override
            public void addLenient(Headers.Builder builder, String name, String value) {
                builder.addLenient(name, value);
            }

            @Override
            public void setCache(Builder builder, InternalCache internalCache) {
                builder.setInternalCache(internalCache);
            }

            @Override
            public InternalCache internalCache(OkHttpClient client) {
                return client.internalCache();
            }

            @Override
            public boolean connectionBecameIdle(
                    ConnectionPool pool, RealConnection connection) {
                return pool.connectionBecameIdle(connection);
            }

            @Override
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值