前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OkHttp系统拦截器

OkHttp系统拦截器

作者头像
曾大稳
发布2018-09-11 10:40:38
8070
发布2018-09-11 10:40:38
举报
文章被收录于专栏:曾大稳的博客曾大稳的博客
代码语言:javascript
复制
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);
 }
RetryAndFollowUpInterceptor

处理重试的一个拦截器,会去处理一些异常,只要不是致命的异常就会重新发起一次请求(把Request给下级),如果是致命的异常就会抛给上一级; 会处理一些重定向等等,比如 3XX 307、407 就会从头部中获取新的路径,生成一个新的请求交给下一级(重新发起一次请求)

BridgeInterceptor

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

CacheInterceptor

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

ConnectInterceptor

findHealthyConnection() 找一个连接,首先判断有没有健康的,没有就创建(建立Scoket,握手连接),连接缓存得到一条结论:OkHttp 是基于原生的 Socket + okio(原生IO的封装)

封装 HttpCodec 里面封装了 okio 的 Source(输入) 和 Sink (输出),我们通过 HttpCodec 就可以操作 Socket的输入输出,我们就可以像服务器写数据和读取返回数据

CallServerInterceptor

写数据和读取数据,写头部信息,写body表单信息等等

连接三个核心类(连接复用)

RealConnection、ConnectionPool、StreamAllocation

RealConnection: 建立连接的一个对象的封装

ConnectionPool:保存了连接

StreamAllocation: 找一些连接,做一下封装

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • RetryAndFollowUpInterceptor
  • BridgeInterceptor
  • CacheInterceptor
  • ConnectInterceptor
  • CallServerInterceptor
  • 连接三个核心类(连接复用)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档