目录
1.RetryAndFollowUpInterceptor拦截器的简介
2.RetryAndFollowUpInterceptor具体实现
2.3.3.RouteException和IOException重试连接
2.3.5.isRecoverable()检测是否是不可恢复异常
1.RetryAndFollowUpInterceptor拦截器的简介
RetryAndFollowUpInterceptor拦截器可以通过源码的备注查看到此拦截器主要是处理连接失败重试(Retry)和重定向(FollowUp)的,此拦截器是第一个执行的系统拦截器;
2.RetryAndFollowUpInterceptor具体实现
2.1具体实现了哪些部分
a.创建了StreamAllocation对象;
b.递归的方式不断的执行下一个拦截器,直到CallServerInterceptor连接服务器拦截器请求服务器获取Response;
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
c.在成功获取Response,检查Response是否需要进行重定向;
Request followUp = followUpRequest(response);
2.2.创建StreamAllocation对象
在intercept()方法中创建StreamAllocation对象,StreamAllocation类主要处理Connections、Streams和Calls三个实体之间的关系,在ConnectInterceptor拦截器中我们会看到具体调用StreamAllocation对象执行newStream()方法创建HttpStream对象,HttpStream接口对象主要指基于HTTP1.X协议的发送HTTP 1.1消息的Socket连接(HttpStream的实现类Http1xStream)对象或者基于HTTP2.X和SPDY协议的HTTP流(HttpStream的实现类Http2xStream),详细介绍不是本篇重点;
StreamAllocation:https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/internal/connection/StreamAllocation.java
2.3递归执行网络请求返回Response
2.3.1.递归具体执行代码
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
具体的调用顺序如下,直到执行到最后一个拦截器执行网络请求,返回Response;
1.RealCall类中执行chain.proceed()方法递归调用第一步
private Response getResponseWithInterceptorChain() throws IOException {
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
2.RealInterceptorChain类中proceed()方法执行拦截器interceptor.intercept(next)方法
public Response proceed(Request request, StreamAllocation streamAllocation, HttpStream httpStream,
Connection connection) throws IOException {
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpStream, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
return response;
}
3.拦截器类中intercept()方法执行chain.proceed()方法
@Override public Response intercept(Chain chain) throws IOException {
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
2.3.2.重连机制
以上拦截器调用顺序;
通过上面的拦