OkHttp的拦截器简介

OkHttp源码中有3个关于网络连接的核心类:RealConnection、ConnectionPool、StreamAllocation

RealConnection: 建立连接

ConnectionPool:保存连接

StreamAllocation: 流分配,封装连接

RealCall类的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, this, eventListener, client.connectTimeoutMillis(),
      client.readTimeoutMillis(), client.writeTimeoutMillis());

  return chain.proceed(originalRequest);
}

可以看到,不分析自定义的拦截器时,拦截器的顺序依次是:

1.RetryAndFollowUpInterceptor 重试拦截器

2.BridgeInterceptor 桥拦截器

3.CacheInterceptor 缓存拦截器

4.ConnectInterceptor 连接拦截器

5.CallServerInterceptor 请求响应拦截器

1.RetryAndFollowUpInterceptor

处理重试的一个拦截器,处理一些异常和重定向。处理异常,只要不是致命的异常就会重新发起一次请求,将Request给下级,如果是致命的异常就会抛给上一级;

处理重定向,比如 3XX 307、407 就会从头部中获取新的路径,生成一个新的请求交给下一级,即重新发起一次请求。

2.BridgeInterceptor

做一些简单的处理,设置一些通用的请求头,Content-Type Connection Content-Length Cookie,做一些返回的处理,如果返回的数据被压缩了采用 ZipSource , 保存 Cookie

3.CacheInterceptor

在缓存可用的情况下,读取本地的缓存的数据,如果没有直接去服务器获取;如果有,首先判断有没有缓存策略,然后判断有没有过期,如果没有过期直接拿缓存,如果过期了,需要添加一些之前头部信息,这个时候后台有可能会给你返回 304,代表还是可以拿本地缓存,每次读取到新的响应后做一次缓存。

4.ConnectInterceptor

findHealthyConnection() 找一个连接,首先判断有没有健康的,没有就创建(建立Scoket,握手连接),连接缓存。

从这里可以看出,OkHttp 是基于原生的Socket + okio(原生IO的封装)

5.CallServerInterceptor

发送请求,获取响应数据(即写数据和读取数据)

OkHttp中 addInterceptor 和 addNetworkInterceptor 的区别?

addInterceptor(应用拦截器):在RetryAndFollowUpInterceptor之前添加,也可不添加

1.不需要担心中间过程的响应,如重定向和重试

2.总是只调用一次,即使HTTP响应是从缓存中获取

3.观察应用程序的初衷. 不关心OkHttp注入的头信息如: If-None-Match

4.允许短路而不调用 Chain.proceed(),即中止调用

5.允许重试,使 Chain.proceed()调用多次

addNetworkInterceptor(网络拦截器):在ConnectInterceptor和CallServerInterceptor之间添加

1.能够操作中间过程的响应,如重定向和重试

2.当网络短路而返回缓存响应时不被调用

3.只观察在网络上传输的数据

4.携带请求来访问连接

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值