OKHttp开源框架学习九:拦截器之ConnectInterceptor

目录

系列文章:

代码:

总结:

总结2:


系列文章:

OKHttp开源框架学习一:同步请求总结

OKHttp开源框架学习二:异步请求总结

OKHttp开源框架学习三:任务调度核心类Dispatcher

OKHttp开源框架学习四:拦截器

OKHttp开源框架学习五:拦截器之RetryAndFollowUpInterceptor

OKHttp开源框架学习六:拦截器之BridgeInterceptor

OKHttp开源框架学习七:缓存策略源码分析

OKHttp开源框架学习八:拦截器之CacheInterceptor

OKHttp开源框架学习九:拦截器之ConnectInterceptor

OKHttp开源框架学习十:ConnectionPool连接池

OKHttp开源框架学习十一:拦截器之CallServerInterceptor

Okhttp总结

代码:

 @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.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

总结:

1、ConnectInterceptor获取Interceptor传过来的StreamAllocation,streamAllocation.newStream()

2、将刚才创建的用于网络IO的RealConnection对象,以及对于与服务器交互最为关键的HttpCodec等对象传递给后面的拦截器

我们来看newStream()方法:

public HttpCodec newStream(
      OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    int connectTimeout = chain.connectTimeoutMillis();
    int readTimeout = chain.readTimeoutMillis();
    int writeTimeout = chain.writeTimeoutMillis();
    boolean connectionRetryEnabled = client.retryOnConnectionFailure();

    try {
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, connectionRetryEnabled, doExtensiveHealthChecks);
      HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);

      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
  }

总结2:

1、创建一个RealConnection对象

2、选择不同的连接方式:一种是socket连接,另一种是tunnel隧道连接

3、调用CallServerInterceptor

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值