业余时间把源码clone下来大致溜了一遍,并且也参阅了其余大神的博客,在这里把自己的心得记录下来共享之,如有不当的地方欢迎批评指正。本文是Okttp源码解析系列的第一篇,不会深入写太多的东西,本篇只是从代码流程上简单的做个梳理,算是为后面的系列博文做个铺垫。

网络请求其实笼统的说一句废话就是发送请求(Request)并接受响应(Response)的过程,当然内部细节在此处不深究

Okhttp完成一个网络请求无非也是这样,一行代码就可以概括(这里先分析同步调用):

Response response = new OkHttpClient().newCall(request).execute();

所以沿着这段代码的调用过程,抽丝剥茧,很容易得出Okhttp的执行流程,newCall()返回的是一个RealCall对象,该对象的execute()方法如下:

public Call newCall(Request request) {
    return new RealCall(this, request, false /* for web socket */);
  }

  public Response execute() throws IOException {
    //省略部分与本文无关的代码
    try {
      //把当前的RealCall对象交给dispatcher保存
      client.dispatcher().executed(this);
      //调用getResponseWithInterceptorChain()来返回结果
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } finally {
      client.dispatcher().finished(this);
    }
  }

很简单上面的两个方法也就做了如下几点功能

1)需要事先组织Request请求对象,该对象包含了请求的url,请求体等内容

2) 将Request对象交给Call对象(RealCall)

3) 执行RealCall对象的execute方法,该方最终返回服务器的响应内容Response对象。

该Response对象是通过getResponseWithInterceptorChain()方法返回而来的!下面就着重看看这个方法都做了些神马功能!

 final Request originalRequest;//通过newCall方法传过来

   Response getResponseWithInterceptorChain() throws IOException {
    List<Interceptor> interceptors = new ArrayList<>();
    //获取用户自定义的拦截器对象:也可以不设置
    interceptors.addAll(client.interceptors());
    //以下拦截器是Okhttp内置的拦截器
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    //将拦截器集合交给RealInterceptorChain这个Chain对象来处理
    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    //执行
    return chain.proceed(originalRequest);
  }

这个方法从代码上来看也很简单,就是将客户端自定义的拦截器(此处先不管Interceptor对象是来干什么的,先当做普通的Java对象类看待)和Okhttp内置的拦截器放到一个List集合interceptors里面,然后跟最初构建的Request对象一块创建了RealInterceptorChain对象,RealInterceptorChain是Chain接口的实现类。这样就把

一系列拦截器组合成一个链跟请求绑定起来,最终调用RealInterceptorChain的proceed来返回一个Response;

简单用图来表示一下此时这个链的关系,可以如下表示:

那么怎么样让 这些拦截器对象逐一运行呢?getResponseWithInterceptorChain方法的最后调用了RealInterceptorChain的proceed方法,该方法直接调用了该对象的重载方法:


//正式开始调用拦截器工作
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,RealConnection connection){

    //省略部分与本文无关的代码

    // 调用链中的下一个拦截器
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

   //确保每个拦截器都调用了proceed方法()
      if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }
   //省略部分与本文无关的代码
    return response;
  }

剔除了与本文无关紧要的代码之后,上面的代码意思也很明显,在总结上面的方法之前看看RealInterceptorChain的构造器是都做了什么初始化工作

//拦截器当前索引
 private final int index;
 private final Request request;

 public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request) {
    this.interceptors = interceptors;
   //省略部分与本文无关的代码
    this.index = index;//0
    this.request = request;
  }

通过其构造函数可以RealInterceptorChain有一个index变量获取拦截器列表中对应位置的拦截器对象,但是procced方法并没有用for循环来遍历interceptors集合,而是重新new 一个RealInterceptorChain对象,且新对象的index在原来RealInterceptorChain对象index之上进行index+1,并把新的拦截器链对象RealInterceptorChain交给当前拦截器Interceptor 的intercept方法:

//生成新的拦截器链对象
 RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    //开始执行拦截:将新的next对象交给interceptor处理
    Response response = interceptor.intercept(next);

抛却自定义的拦截器对象先不谈,上面的表述可以用下图来表示:

既然Interceptor的intercept方法接受的是一个新RealInterceptorChain对象,通过上面的代码来看目前index只能达到index=1,那么剩下的CacheIntercept对象是如何调用的呢?其实也可以大胆的猜测一下:

既然拦截器组成了一个链,那么肯定是 第一个内置拦截器RetryAndFollowUpInterceptor对象接受的Chain对象在intercept方法里面继续对新的Chain做了遍历下一个拦截器的操作!

所以大致看下RetryAndFollowUpInterceptor对象的intercept方法都做了神马:

Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
   //省略部分与本文无关的代码

    Response priorResponse = null;
    while (true) {//死循环
     //省略部分与本文无关的代码
      //上一个拦截器返回的响应对象
      Response response = null;
      //省略部分与本文无关的代码
      //继续执行下一个chain的下一个
     response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
      //省略部分与本文无关的代码

      Request followUp = followUpRequest(response);

      if (followUp == null) {
        //返回return
        return response;
      }

     //省略部分与本文无关的代码
      priorResponse = response;
    }//end while
  }

可以发现RetryAndFollowUpInterceptor对象的intercept有一个while(true)的循环,在循环里面有一行很重要的代码:

     response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);

看!上面的也跟getResponseWithInterceptorChain()一样调用了proceed方法,根据上面的的讲解:调用Chain的proceed方法的时候会新生成一个RealInterceptorChain,其index的值是上一个拦截器所持有的Chain的index+1,这样就确保拦截器链逐条运行。查看BridgeInterceptor、CacheInterceptor等Okhttp内置拦截器就可以印证这一点:在它们intercept的内部都调用了chain.proceed()方法,且每次调用都在会创建一个RealInterceptorChain对象(当然最后一个拦截器CallServerInterceptor除外)!所以拦截器的工作流方式可以用如下图来表示:



如果从发起请求Request到得到响应Response的过程,加上拦截器链的话工作在内,其i整体执行过程就是如下了:

这也是为什么RealInterceptorChain的procced方法中有如下的异常抛出,目的就是为了让拦截器链一个个执行下去,确保整个请求过程的完成:

if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

也即是说自定义的拦截器Interceptor必须调Chain的proceed一次(可多次调用),那么到此为止一个完 整的Okttp(同步)请求的流程就已经完成,那么就简单的用一个流程图来总结本文的说明吧:

Okhttp源码简单解析(一)的更多相关文章

  1. node-pre-gyp以及node-gyp的源码简单解析(以安装sqlite3为例)

    title: node-pre-gyp以及node-gyp的源码简单解析(以安装sqlite3为例) date: 2020-11-27 tags: node native sqlite3 前言 简单来 ...

  2. springmvc(2)Controller源码简单解析

    前面简单的分析了一下DispatcherServlet,接下来分析一下Controller,在web的MVC中,Controller就是其中的C,启动的一些页面逻辑处理,页面映射的功能: 首先看看超类 ...

  3. ForkJoinPool源码简单解析

    ForkJoin框架之ForkJoinTask  java  阅读约 62 分钟 前言 在前面的文章"CompletableFuture和响应式编程"中提到了ForkJoinTas ...

  4. StringBudiler源码简单解析

    StringBudiler源码 继承关系树 底层实现 默认容量() 特别的添加方法(append) 1.继承关系树 继承自AbstractStringBuilder与StringBuffer同族 2. ...

  5. springmvc(1)DispatcherServlet源码简单解析

    springmvc的简单配置 1.首先需要在web.xml中配置DispatcherServlet,这个类是springmvc的核心类,所以的操作都是由这里开始,并且大部分都是在这里面实现的,比如各种 ...

  6. OKHttp源码解析

    http://frodoking.github.io/2015/03/12/android-okhttp/ Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 A ...

  7. 【转载】okhttp源码解析

    转自:http://www.open-open.com/lib/view/open1472216742720.html https://blog.piasy.com/2016/07/11/Unders ...

  8. FFmpeg的HEVC解码器源码简单分析:解析器(Parser)部分

    ===================================================== HEVC源码分析文章列表: [解码 -libavcodec HEVC 解码器] FFmpeg ...

  9. Retrofit源码设计模式解析(下)

    本文将接着<Retrofit源码设计模式解析(上)>,继续分享以下设计模式在Retrofit中的应用: 适配器模式 策略模式 观察者模式 单例模式 原型模式 享元模式 一.适配器模式 在上 ...

随机推荐

  1. php内存管理机制、垃圾回收机制

    一.内存管理机制 先看一段代码: <?php //内存管理机制 var_dump(memory_get_usage());//获取内存方法,加上true返回实际内存,不加则返回表现内存 $a = ...

  2. mapreduce 运行-指定各种运行参数

    mapreduce指定参数 mapreduce在运行的时候可以指定各种参数,这样可以根据实际的应用场景做一下相关的调整 1.指定运行时cpu的个数 hadoop jar hadoop-core-0.1 ...

  3. Java 基础总结(二)

    本文参见:http://www.cnblogs.com/dolphin0520/category/361055.html 1. 字节流与和字符流 1). 字符流操作时使用了缓冲区,而在关闭字符流时会强 ...

  4. C# 异步同步调用

    本文将主要通过“同步调用”.“异步调用”.“异步回调”三个示例来讲解在用委托执行同一个“加法类”的时候的的区别和利弊. 首先,通过代码定义一个委托和下面三个示例将要调用的方法: /*添加的命名空间 u ...

  5. level-13

    如何调试IE浏览器 1.打开IE浏览器,F12打开开发者模式.(针对IE7及以上) 2.针对IE6浏览器.使用虚拟机或者用ietester 什么是CSS hack?在 CSS 和 HTML里如何写 h ...

  6. Zabbix Windos agent 安装

    系统:Windos 2008 R2 x64 服务:Zabbix_agents_3.0.4.win 一.安装Zabbix_agents_3.0.4.win 1.下载Zabbix_agents_3.0.4 ...

  7. HDU 1241 油田

    这道题明明很简单但不知道为什么运行结果一直错,但提交却是对的!代码真是神奇,不过我猜测可能是提上给出的数据错了,可能提上给的数据m和n后多给了一个空格或回车,但题的数据没有 #include<s ...

  8. Spring Boot 快速入门(IDEA)

    从字面理解,Boot是引导的意思,因此SpringBoot帮助开发者快速搭建Spring框架:SpringBoot帮助开发者快速启动一个Web容器:SpringBoot继承了原有Spring框架的优秀 ...

  9. 并发-ConcurrentHashMap源码分析

    ConcurrentHashMap 参考: http://www.cnblogs.com/chengxiao/p/6842045.html https://my.oschina.net/hosee/b ...

  10. eclipse官网下载

    Provided by IBM Cloud Eclipse IDE for Java Developers http://eclipse.bluemix.net/packages/photon/dat ...