OKhttp源码解析---Request执行

执行一个request是调用它的enqueue并传递一个回调

        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure---" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    String str = response.cacheResponse().toString();
                    System.out.println("cache---" + str);
                } else {
                    response.body().string();
                    String str = response.networkResponse().toString();
                    System.out.println("network---" + str);
                }
            }
        });
有前面分析可知这里的mcall是RealCall

  @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }
创建一个AsyncCall,调用dispatcher把前面创建的AsyncCall入队列

AsyncCall继承于NamedRunnable实现了Runnable接口

我们看下dispatcher的enque

  synchronized void enqueue(AsyncCall call) {
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      runningAsyncCalls.add(call);
      executorService().execute(call);
    } else {
      readyAsyncCalls.add(call);
    }
  }
如果请求总数小于max且当前连接请求数小于maxRequestPerHost,则添加到runningAsyncCalls,并调用executorService然后执行execute
  public synchronized ExecutorService executorService() {
    if (executorService == null) {
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
  }
execute最终执行我们前面AsyncCall的execute方法

 @Override protected void execute() {
      boolean signalledCallback = false;
      try {
        Response response = getResponseWithInterceptorChain();
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          responseCallback.onResponse(RealCall.this, response);
        }
      } catch (IOException e) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }
  }
这里首先调用 getResponseWithInterceptorChain,getResponseWithInterceptorChain会通过一系列的拦截器实现网络请求逻辑,而异步则是通过前面的 ExecutorService 实现。然后根据返回的结果调用回调函数响应的接口,如成功则调用onResponse等

private Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!retryAndFollowUpInterceptor.isForWebSocket()) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(
        retryAndFollowUpInterceptor.isForWebSocket()));

    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

这里主要是添加一系列的拦截器,首先添加的是我们设置的,然后分别添加如下拦截器:

interceptors:代码中添加的应用拦截器

RetryAndFollowUpInterceptor:负责失败重连以及重定向的

BridgeInterceptor:主要负责构造请求,如请求头,以及构造请求结果和处理如是否有gzip压缩等

CacheInterceptor:缓存处理,读取缓存,缓存更新等

ConnectInterceptor:负责和服务器建立连接

networkInterceptors:代码中设置的网络拦截器

CallServerInterceptor:负责跟服务器交互,发送请求,获取响应

RealInterceptorChain:负责执行上面的这些拦截器

应用拦截器和网络拦截器的特点

应用拦截器:主要用于查看请求信息及返回信息,如链接地址、头信息、参数信息等
        *不必要担心响应和重定向之间的中间响应。
        *通常只调用一次,即使HTTP响应是通过缓存提供的。
        *遵从应用层的最初目的。与OkHttp的注入头部无关,如If-None-Match。
        *允许短路而且不调用Chain.proceed()。
        *允许重试和多次调用Chain.proceed()。
网络拦截器:可以添加、删除或替换请求头信息,还可以改变的请求携带的实体
        *允许像重定向和重试一样操作中间响应。
        *网络发生短路时不调用缓存响应。
        *在数据被传递到网络时观察数据。
        *有权获得装载请求的连接。

具体参考:

http://blog.csdn.net/oyangyujun/article/details/50039403

http://blog.csdn.net/tangxl2008008/article/details/51887285

他们的作用我们也可以从他们所出的层次可以看出来

接下来以一张图概括整个调用流程,后面在单独分析各个拦截器

代码最后把前面添加的拦截器以及原始的请求作为参数构造了一个RealInterceptorChain,index为0,然后调用它的proceed方法

  @Override public Response proceed(Request request) throws IOException {
    return proceed(request, streamAllocation, httpStream, connection);
  }
public Response proceed(Request request, StreamAllocation streamAllocation, HttpStream httpStream,
      Connection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpStream != null && !sameConnection(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpStream != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpStream, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpStream != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    return response;
  }
这里首先判断index是否大于拦截器个数,然后判断当前是否已经建立了一个http流,且是否请求路径一致

然后新建一个RealInterceptorChain传递index+1为参数,其他参数保持不变

最后获取当前index(0)出的拦截器,并调用它的intercept方法

这里获取到的拦截器就是RetryAndFollowUpInterceptor,下一篇我们看他都做了什么处理。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值