一篇搞定okHttp三

本文深入解析OKHttp的ConnectInterceptor连接池拦截器和CallServerInterceptor服务请求拦截器,阐述它们在网络请求中的作用。ConnectInterceptor负责创建和回收网络连接,CallServerInterceptor则负责发起请求和接收响应。此外,还探讨了Response对象只能使用一次的原因,涉及到源码分析和资源管理。

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

OKHttp系列十一、ConnectInterceptor连接池拦截器

包含两个方面的内容,一是网络连接角度发挥作用的网络拦截器,二是从连接池的操作角度发挥作用的拦截器。
1、网络连接拦截器,ConnectInterceptor.java的代码很少,逻辑比较简单:

public final class ConnectInterceptor implements Interceptor {
    public final OkHttpClient client;
    public ConnectInterceptor(OkHttpClient client) {
        this.client = client;
    }
    @Override public Response intercept(Chain chain) throws IOException {
        RealInterceptorChain realChain = (RealInterceptorChain) chain;
        Request request = realChain.request();
        StreamAllocation streamAllocation = realChain.streamAllocation();
        boolean doExtensiveHealthChecks = !request.method().equals("GET");
        HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
        RealConnection connection = streamAllocation.connection();
        return realChain.proceed(request, streamAllocation, httpCodec, connection);
    }
}

分析入口依然是我们最熟悉的地方:intercept();该方法的前三行分别创建了三个对象。这里我们重点关注StreamAllocation.
StreamAllocation的作用:用来建立执行OKHttp请求所需要的网络参数组件,分配Stream。
前面在RetryAndFollowUpInterceptor重定向拦截器里面我们家提到过,StreamAllocation在哪里被创建出来,但是真正的使用是在ConnectInterceptor里面,这不,现在我们就在分析这块了。
StreamAllocation对象创建完成后,我们通过下面这段代码进行使用:

boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);

这里httpCodec对象是用来编码我们的Request和解码我们的response对象的。

RealConnection connection = streamAllocation.connection();

上面这行代码中RealConnection对象的作用——用来进行实际上的网络IO传输。
最后再通过realChain.proceed()来进行来节气的调用。

总结:

1、ConnectInterceptor获取从RetryAndFollowUpInterceptor重定向拦截器传过来的StreamAllocation对象,然后创建HttpCodec对象和RealConnection对象。
    HttpCodec对象主要用于编码我们的Request和解码我们的response对象;RealConnection对象用来进行实际上的网络IO传输。
2、调用realChain.proceed()方法将我们刚刚创建的用于编码我们的Request和解码我们的response对象的HttpCodec对象和
    用来进行实际上的网络IO传输的RealConnection对象传递给下一个拦截器CallServerInterceptor。

在前面的源码中,有一个很重要的方法:streamAllocation.newStream()。现在我们再来看看这个方法的具体实现:

public HttpCodec newStream(OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    int connectTimeout = chain.connectTimeoutMillis();
    int readTimeout = chain.readTimeoutMillis();
    int writeTimeout = chain.writeTimeoutMillis();
    int pingIntervalMillis = client.pingIntervalMillis();
    boolean connectionRetryEnabled = client.retryOnConnectionFailure();
    try {
        RealConnec
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_深巷的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值