返回

OkHttp - ConnectInterceptor(连接拦截器)源码分析

Android

在网络访问中,连接是一个非常重要的环节,它决定了网络请求的效率和成功率。ConnectInterceptorOkHttp中负责连接的拦截器,本文将通过分析ConnectInterceptor的源码,来深入了解OkHttp是如何进行连接的。

  1. ConnectInterceptor的简介

    • ConnectInterceptorOkHttp中负责连接的拦截器,它是OkHttp连接过程中的第一个拦截器。
    • ConnectInterceptor的作用是创建连接并将其传递给后续的拦截器。
  2. ConnectInterceptor的源码分析

    • ConnectInterceptor的源码位于okhttp3.OkHttpClient类中,源码如下:
    public void intercept(Chain chain) throws IOException {
        final RealInterceptorChain realChain = (RealInterceptorChain) chain;
        StreamAllocation streamAllocation = realChain.streamAllocation;
        RealConnection connection = streamAllocation.connection();
        Route selectedRoute = streamAllocation.route();
        int connectTimeout = streamAllocation.connectionSettings().connectTimeoutMillis();
        if (connection != null) {
            if (selectedRoute.address().equals(connection.route().address()) && !connection.transmitters().isEmpty()) {
                realChain.proceed(chain.request(), connection);
                return;
            } else {
                streamAllocation.noNewStreams();
            }
        }
        // Find a connection from the pool, create one if necessary.
        synchronized (OkHttp.class) {
            // We might have created a connection while waiting for a barrier.
            connection = streamAllocation.connection();
            if (connection == null) {
                connection = createIfNecessary(
                        streamAllocation, selectedRoute, connectTimeout, realChain);
            }
        }
        realChain.proceed(chain.request(), connection);
    }
  • 从源码中可以看出,ConnectInterceptor主要做了以下几件事:
    • 获取StreamAllocation对象,StreamAllocation对象管理着与服务器的连接。
    • 获取RealConnection对象,RealConnection对象代表了一个与服务器的连接。
    • 获取Route对象,Route对象代表了客户端到服务器的路由信息。
    • 获取连接超时时间。
    • 检查RealConnection对象是否存在,如果存在,则检查Route对象是否与RealConnection对象的Route对象相同,如果相同,则将请求交给后续的拦截器处理,否则关闭RealConnection对象。
    • 如果RealConnection对象不存在,则创建新的RealConnection对象。
    • 将请求交给后续的拦截器处理。
  1. ConnectInterceptor的原理

    • ConnectInterceptor的原理是通过StreamAllocation对象来管理与服务器的连接。StreamAllocation对象是一个连接池,它负责创建和管理连接。当需要建立连接时,ConnectInterceptor会先从连接池中查找是否有可用的连接,如果有,则直接使用该连接,否则就创建一个新的连接。
  2. ConnectInterceptor的使用

    • ConnectInterceptorOkHttp中默认的连接拦截器,它不需要手动添加。如果需要自定义连接过程,可以实现自己的连接拦截器,并在OkHttpClient中添加。
  3. 总结

    • ConnectInterceptorOkHttp中负责连接的拦截器,它通过StreamAllocation对象来管理与服务器的连接。ConnectInterceptor的原理是先从连接池中查找是否有可用的连接,如果有,则直接使用该连接,否则就创建一个新的连接。ConnectInterceptorOkHttp中默认的连接拦截器,不需要手动添加。