okhttp之旅(七)--ConnectInterceptor连接拦截器

系统学习详见OKhttp源码解析详解系列

1 述

在RetryAndFollowUpInterceptor里初始化了一个StreamAllocation对象,我们说在这个StreamAllocation对象里初始化了一个Socket对象用来做连接,但是并没有
真正的连接,等到处理完hader和缓存信息之后,才调用ConnectInterceptor来进行真正的连接

public final class ConnectInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        RealInterceptorChain realChain = (RealInterceptorChain) chain;
        Request request = realChain.request();
        StreamAllocation streamAllocation = realChain.streamAllocation();

        // We need the network to satisfy this request. Possibly for validating a conditional GET.
        //我们需要网络来满足这个要求。 可能用于验证条件GET
        boolean doExtensiveHealthChecks = !request.method().equals("GET");
        //创建输出流
        HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
        //建立连接
        RealConnection connection = streamAllocation.connection();

        return realChain.proceed(request, streamAllocation, httpCodec, connection);
    }
}
  • ConnectInterceptor在Request阶段建立连接,处理方式也很简单,创建了两个对象:
  • HttpCodec:用来编码HTTP requests和解码HTTP responses
  • RealConnection:连接对象,负责发起与服务器的连接。
  • 这里事实上包含了连接、连接池等一整套的Okhttp的连接机制

你可能感兴趣的:(okhttp之旅(七)--ConnectInterceptor连接拦截器)