OkHttp3源码详解(三) 拦截器-RetryAndFollowUpInterceptor
最大恢复追逐次数:
private static final int MAX_FOLLOW_UPS = ;
处理的业务:
- 实例化StreamAllocation,初始化一个Socket连接对象,获取到输入/输出流()基于Okio
- 开启循环,执行下一个调用链(拦截器),等待返回结果(Response)
- 如果发生错误,判断是否继续请求,否:退出
- 检查响应是否符合要求,是:返回
- 关闭响应结果
- 判断是否达到最大限制数,是:退出
- 检查是否有相同连接,是:释放,重建连接
- 重复以上流程
源码
@Override
public Response intercept(Chain chain) throws IOException {
//
Request request = chain.request();
// 1. 初始化一个socket连接对象
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace); int followUpCount = ;
Response priorResponse = null;
while (true) {
//
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
} Response response = null;
boolean releaseConnection = true;
try {
// 2. 执行下一个拦截器,即BridgeInterceptor
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
// 3. 如果有异常,判断是否要恢复
if (!recover(e.getLastConnectException(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
} // Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
// 4. 检查是否符合要求
Request followUp = followUpRequest(response); if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
// 返回结果
return response;
}
// 5. 不符合,关闭响应流
closeQuietly(response.body());
// 6. 是否超过最大限制
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
} if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
// 7. 是否有相同的连接
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(followUp.url()), callStackTrace);
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response
+ " didn't close its backing stream. Bad interceptor?");
} request = followUp;
priorResponse = response;
}
}
初始化连接对象
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
注意:此处还没有真正的去建立连接,只是初始化一个连接对象
继续下一个拦截器
上面一步初始化好后,将继续执行下一个连接器BridgeInterceptor,
// 这里有个很重的信息,即会将初始化好的连接对象传递给下一个拦截器,也是贯穿整个请求的连击对象,
// 上文我们说过,在拦截器执行过程中,RealInterceptorChain的几个属性字段会一步一步赋值
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
抛出异常
如果抛出异常,将判断是否能够继续连接,以下情况不在,重试:
/**
* 不在继续连接的情况:
* 1. 应用层配置不在连接,默认为true
* 2. 请求Request出错不能继续使用
* 3. 是否可以恢复的
* 3.1、协议错误(ProtocolException)
3.2、中断异常(InterruptedIOException)
3.3、SSL握手错误(SSLHandshakeException && CertificateException)
3.4、certificate pinning错误(SSLPeerUnverifiedException)
* 4. 没用更多线路可供选择
*/
private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);
// 1. 应用层配置不在连接,默认为true
// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false; // 2. 请求Request出错不能继续使用
// We can't send the request body again.
if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false; // 是否可以恢复的
// This exception is fatal.
if (!isRecoverable(e, requestSendStarted)) return false; // 4. 没用更多线路可供选择
// No more routes to attempt.
if (!streamAllocation.hasMoreRoutes()) return false; // For failure recovery, use the same route selector with a new connection.
return true;
}
http://lowett.com/categories/Android/Okhttp3/
OkHttp3源码详解(三) 拦截器-RetryAndFollowUpInterceptor的更多相关文章
- OkHttp3源码详解(三) 拦截器
1.构造Demo 首先构造一个简单的异步网络访问Demo: OkHttpClient client = new OkHttpClient(); Request request = new Reques ...
- OkHttp3源码详解(一) Request类
每一次网络请求都是一个Request,Request是对url,method,header,body的封装,也是对Http协议中请求行,请求头,实体内容的封装 public final class R ...
- OkHttp3源码详解(五) okhttp连接池复用机制
1.概述 提高网络性能优化,很重要的一点就是降低延迟和提升响应速度. 通常我们在浏览器中发起请求的时候header部分往往是这样的 keep-alive 就是浏览器和服务端之间保持长连接,这个连接是可 ...
- OkHttp3源码详解(六) Okhttp任务队列工作原理
1 概述 1.1 引言 android完成非阻塞式的异步请求的时候都是通过启动子线程的方式来解决,子线程执行完任务的之后通过handler的方式来和主线程来完成通信.无限制的创建线程,会给系统带来大量 ...
- OkHttp3源码详解(二) 整体流程
1.简单使用 同步: @Override public Response execute() throws IOException { synchronized (this) { if (execut ...
- 详解Mybatis拦截器(从使用到源码)
详解Mybatis拦截器(从使用到源码) MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能. 本文从配置到源码进行分析. 一.拦截器介绍 MyBatis 允许你在 ...
- spring事务详解(三)源码详解
系列目录 spring事务详解(一)初探事务 spring事务详解(二)简单样例 spring事务详解(三)源码详解 spring事务详解(四)测试验证 spring事务详解(五)总结提高 一.引子 ...
- Activiti架构分析及源码详解
目录 Activiti架构分析及源码详解 引言 一.Activiti设计解析-架构&领域模型 1.1 架构 1.2 领域模型 二.Activiti设计解析-PVM执行树 2.1 核心理念 2. ...
- 源码详解系列(七) ------ 全面讲解logback的使用和源码
什么是logback logback 用于日志记录,可以将日志输出到控制台.文件.数据库和邮件等,相比其它所有的日志系统,logback 更快并且更小,包含了许多独特并且有用的特性. logback ...
随机推荐
- [BZOJ 5323][Jxoi2018]游戏
传送门 \(\color{green}{solution}\) 它每次感染的人是它的倍数,那么我们只需要找出那些除了自己以外在\(l\), \(r\)内没有别的数是 它的约数的数,在这里称其为关键数. ...
- noip | 题目 | noip数据 收集站 | noipdata
这是什么 一个NOIP历年比赛数据及题目的收集站,方便大家查找使用 网站链接:https://noipdata.github.io 点击这里立即跳转 新连接:noipdata.rcxzsc.com 点 ...
- USACO The Lazy Cow
题目描述 这是一个炎热的夏天,奶牛贝茜感觉到相当的疲倦而且她也特别懒惰.她要在她的领域中找到一个合适的位置吃草,让她能吃到尽可能多的美味草并且尽量只在很短的距离.奶牛贝茜居住的领域是一个 N×N 的矩 ...
- docker仓库harbor镜像列表获取命令
2019-03-14 搭建好docker仓库harbor之后,在服务器上获取harbor的所有镜像列表命令 curl -u "harbor账号:密码" -X GET -H &quo ...
- 学习Linux最简单的方法
大多数初学者在刚刚接触Linux都会有非常陌生的感觉.往往会有一些疑惑和问题.而我们就沿着这些问题,从远及近,从宏观到微观来理解Linux的简洁和美丽. 问题1:Winows有注册表,为什么Linux ...
- redux在componentDidMount中出现的问题 --- state 不变
遇到这样一个问题: 在组件的componentDidMount中,我需要使用到redux中存储的某个状态. 但是有趣的是,当我再render中使用相同的状态时,状态会改变,但是在conponentDi ...
- android开发中的BaseAdapter之理解(引用自网络,总结的很好,谢谢)
android中的适配器(Adapter)是数据与视图(View)之间的桥梁,用于对要显示的数据进行处理,并通过绑定到组件进行数据的显示. BaseAdapter是Android应用程序中经常用到的基 ...
- 如何自己编译生成hadoop的eclipse插件,如hadoop-eclipse-plugin-2.6.0.jar
不多说,直接上干货! 如何自己编译生成Eclipse插件,如hadoop-eclipse-plugin-2.6.0.jar 一.相关软件的安装和配置 (一)JDK的安装和配置 Jdk 1.7*安装并配 ...
- python-Event事件处理进程同步
#!/usr/bin/python from multiprocessing import Process,Event import os,time def A(e): print "blo ...
- git 学习之撤销和删除
在实际的工作和学习中我们经常的会对文件进行修改,但是或多或少的就会发现由于某些原因修改是错误的这时候就需要对所做的修改进行撤销,更或者某些时候需要对文件进行删除.本节就会告诉大家如何操作. 撤销操作 ...