美文网首页
拆轮子:OkHttp 的源码解析(四):拦截器(Intercep

拆轮子:OkHttp 的源码解析(四):拦截器(Intercep

作者: ldlywt | 来源:发表于2017-05-10 18:24 被阅读199次

OkHttp3.7源码分析文章列表如下:
拆轮子:OkHttp 的源码解析(一):概述
拆轮子:OkHttp 的源码解析(二):流程分析
拆轮子:OkHttp 的源码解析(三):任务分发器(Dispatcher)
拆轮子:OkHttp 的源码解析(四):拦截器(Interceptor)

拦截器接口

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();
    Response proceed(Request request) throws IOException;
    Connection connection();
  }
}

okhttp 默认的拦截器

默认的拦截器
  1. retryAndFollowUpInterceptor
  • 在网络请求失败后进行重试
  • 当服务器返回当前请求需要进行重定向时直接发起新的请求,并在条件允许情况下复用当前连接
  1. BridgeInterceptor
  • 设置内容长度,内容编码
  • 设置gzip压缩,并在接收到内容后进行解压。省去了应用层处理数据解压的麻烦
  • 添加cookie
  • 设置其他报头,如User-Agent,Host,Keep-alive等。其中Keep-Alive是实现多路复用的必要步骤
  1. CacheInterceptor
  • 当网络请求有符合要求的Cache时直接返回Cache
  • 当服务器返回内容有改变时更新当前cache
  • 如果当前cache失效,删除
  1. ConnectInterceptor
  • 负责和服务器建立连接
  1. CallServerInterceptor
  • 负责向服务器发送请求数据、从服务器读取响应数据

getResponseWithInterceptorChain() 分析

  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 (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

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

networkInterceptors : 配置 OkHttpClient 时设置的一个拦截器的 List。

这里主要做了如下几件事:

  • 创建一个拦截器集合 ArrayList,向集合中添加一系列拦截器,包括用户自定义的拦截器和框架内部拦截器。
  • 创建一个拦截器链 RealInterceptorChain,并执行拦截器链的 proceed 方法。

责任链模式

下面设计到责任链模式,如果你不知道什么是责任链模式,请点击

Android设计模式源码解析之责任链模式

多个拦截器配置构成一个拦截器链 Interceptor.Chain,环环相扣,最终圆满完成一次网络请求。

借用一张图来表示:

拦截器链.png

如果你还想看每个 Interceptor 的具体分析
或者想看拦截器链的proceed方法
请点击下面博文:
OkHttp 3.7源码分析(二)——拦截器&一个实际网络请求的实现
友情提示:慎点,很容易看晕的,o(╯□╰)o

相关文章

网友评论

      本文标题:拆轮子:OkHttp 的源码解析(四):拦截器(Intercep

      本文链接:https://www.haomeiwen.com/subject/uiegtxtx.html