OKHttp(责任链,拦截器)

116 阅读1分钟

原链接:juejin.cn/post/701551…

image.png

拦截器(无自定义)

  • RetryAndFollowUpInterceptor(重定向/重试拦截器)
  • BridgeInterceptor(桥接拦截器)
  • CacheInterceptor(缓存拦截器)
  • ConnectInterceptor(连接拦截器)
  • CallServerInterceptor(读写拦截器)

RetryAndFollowUpInterceptor:

image.png

  • recover:判断是否重试 image.png
  • isRecoverable:判断是否属于重试异常 image.png
  • 判断是否重定向 image.png followUpRequest方法 image.png

BridgeInterceptor

请求头/响应头拼接封装

CacheInterceptor 缓存拦截器

分析点1 image.png 分析点2 image.png 分析点3 image.png 分析点4 image.png 分析点5 image.png 分析点6 image.png

3.1 第二个if:hasBody和isCacheable

- hasBody

image.png -isCacheable

image.png -cacheWritingResponse 写入缓存(前两判断为true) 非空就使用Okio框架将缓存写到SD卡,写入成功返回写入的数据

3.2 读取缓存 (分析点1)

image.png 缓存工厂 image.png get方法 - > getCandidate 获取缓存

分析点9

Cache-Contro:immutable 响应内容没变取缓存

image.png

分析点10

不满足9时,缓存有效期内就能去缓存

image.png

分析点11

不满足9,10,只要etag(缓存响应),lastModified(最后修改时间),servedDate(响应服务器的时间)任意一个不为空

image.png

ConnectInterceptor(连接拦截器)

主要功能都在streamAllocation.neewStream - >findHealthyConnection - > 死循环 findConnection

image.png

findConnection

image.png 在对应线路都没找到,就开辟新链接,加入线程池并将连接成功后的对象返回 image.png

CallServerInterceptor(读写/请求拦截器)

包括了所有拦截器的设置,主要用于网络请求体以及响应体的封装。请求体请求网络,响应体返回上一级

image.png

image.png

拦截器流程 image.png