Okhttp源码阅读之旅(二)

上一节讲到了OkHttpClient里面的属性。这节就讲到newCall说返回对象的类型Call.

这次我们还是顺着OkHttpClinet的使用作为线索来读。

一个典型的同步方法是

new OkhttpClient().newCall(request).excute();
我们重点来看Call里的execute()使用方法。


public Response execute()
    throws IOException
  {
    synchronized (this)
    {
      if (this.executed) {
        throw new IllegalStateException("Already Executed");
      }
      this.executed = true;
    }
    try
    {
      this.client.getDispatcher().executed(this);
      Response result = getResponseWithInterceptorChain(false);
      if (result == null) {
        throw new IOException("Canceled");
      }
      return result;
    }
    finally
    {
      this.client.getDispatcher().finished(this);
    }
  }

通过DistPatcher(第一节中OkHttpClient的分发器),在getResponseWithInterceptorChain(boolean)前后分别调用executed() finished()方法。

而这段代码的重点是getResponseWithInterceptorChain(boolean)这个方法。

 private Response getResponseWithInterceptorChain(boolean forWebSocket)
    throws IOException
  {
    Interceptor.Chain chain = new ApplicationInterceptorChain(0, this.originalRequest, forWebSocket);
    return chain.proceed(this.originalRequest);
  }

然后我们按图索骥,去研究Interceptor.Chain,它的实现还是在Call这个类型中

class ApplicationInterceptorChain
    implements Interceptor.Chain
  {
    private final int index;
    private final Request request;
    private final boolean forWebSocket;
    
    ApplicationInterceptorChain(int index, Request request, boolean forWebSocket)
    {
      this.index = index;
      this.request = request;
      this.forWebSocket = forWebSocket;
    }
    
    public Connection connection()
    {
      return null;
    }
    
    public Request request()
    {
      return this.request;
    }
    
    public Response proceed(Request request)
      throws IOException
    {
      if (this.index < Call.this.client.interceptors().size())
      {
        Interceptor.Chain chain = new ApplicationInterceptorChain(Call.this, this.index + 1, request, this.forWebSocket);
        Interceptor interceptor = (Interceptor)Call.this.client.interceptors().get(this.index);
        Response interceptedResponse = interceptor.intercept(chain);
        if (interceptedResponse == null) {
          throw new NullPointerException("application interceptor " + interceptor + " returned null");
        }
        return interceptedResponse;
      }
      return Call.this.getResponse(request, this.forWebSocket);
    }
  }

最终是通过Interceptor对象的intercept(chain)方法,获得 interceptedResponse。而interceptor是通过来自client里的interceptor对象。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值