### 前言
回顾:
[Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f)
[Okhttp3源码解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7)
[Okhttp3源码解析(2)-Request分析](https://www.jianshu.com/p/5a85345c8ea7)
[Okhttp3源码解析(3)-Call分析(整体流程)](https://www.jianshu.com/p/4ed79472797a)
[Okhttp3源码解析(4)-拦截器与设计模式](https://www.jianshu.com/p/b8817597f269)

上节讲了拦截器与设计模式,今天讲`RetryAndFollowUpInterceptor`,如果我们没有去自定义拦截器, 那`RetryAndFollowUpInterceptor`是第一个拦截器。

### 初始化
首先先看`RetryAndFollowUpInterceptor`被添加的位置:
![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084744888-554996670.png)
初始化位置:
call实例化方法中:
```
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
}
```

找到了初始化的位置, 下面去`RetryAndFollowUpInterceptor`种分析!

### RetryAndFollowUpInterceptor解析
从上节我们就知道拦截器中的**intercept()是核心!** 这里贴出代码:
```

@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();

StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;

int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}

Response response;
boolean releaseConnection = true;
try {
response = realChain.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.
if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
throw e.getFirstConnectException();
}
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, streamAllocation, 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();
}

Request followUp;
try {
followUp = followUpRequest(response, streamAllocation.route());
} catch (IOException e) {
streamAllocation.release();
throw e;
}

if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}

closeQuietly(response.body());

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());
}

if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
} 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;
}
}
```
我先贴出一个`while循环`的流程图:
![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084745296-805720763.png)

根据流程图和源码可以分析`RetryAndFollowUpInterceptor`主要做了以下内容,**后两点都是发生在`while循环`中**:

- **初始化StreamAllocation 对象**
- **网络请求-chain.proceed() ,对在请求时发生的异常进行捕获以及对应的重连机制**
- **followUpRequest 对响应码进行处理**

下面可以逐块代码分析:
###### 1.初始化StreamAllocation 对象
`StreamAllocation`类是**协调三个实体之间的关系** 三个实体是:`Connections`,`Streams`,`Calls`
我们请求网络时需要传递它
![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084745679-501952792.png)
`StreamAllocation`在这大家简单了解一下就可以了.

###### 2.网络请求时异常捕获-以及重连机制
网络请求如下:
```
response = realChain.proceed(request, streamAllocation, null, null);
```
如果请求发现异常,我们通过try/catch捕获
```
catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
throw e.getFirstConnectException();
}
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, streamAllocation, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
}
```
-`RouteException` 路由异常
- `IOException` IO异常
捕获后都做了`recover()`重连判断,具体代码如下,就不细说了:
```
private boolean recover(IOException e, StreamAllocation streamAllocation,
boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);

// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false;

// 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;

// No more routes to attempt.
if (!streamAllocation.hasMoreRoutes()) return false;

// For failure recovery, use the same route selector with a new connection.
return true;
}
```
这里需要注意的是如果可以重连,执行 continue;
`continue`含义: 继续循环,(不执行 循环体内`continue` 后面的语句,直接进行下一循环)

###### 3.` followUpRequest` 对响应码进行处理

先看看具体`followUpRequest `方法:
```
private Request followUpRequest(Response userResponse, Route route) throws IOException {
if (userResponse == null) throw new IllegalStateException();
int responseCode = userResponse.code();

final String method = userResponse.request().method();
switch (responseCode) {
case HTTP_PROXY_AUTH:
Proxy selectedProxy = route != null
? route.proxy()
: client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
return client.proxyAuthenticator().authenticate(route, userResponse);

case HTTP_UNAUTHORIZED:
return client.authenticator().authenticate(route, userResponse);

case HTTP_PERM_REDIRECT:
case HTTP_TEMP_REDIRECT:
// "If the 307 or 308 status code is received in response to a request other than GET
// or HEAD, the user agent MUST NOT automatically redirect the request"
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
// Does the client allow redirects?
if (!client.followRedirects()) return null;

String location = userResponse.header("Location");
if (location == null) return null;
HttpUrl url = userResponse.request().url().resolve(location);

// Don't follow redirects to unsupported protocols.
if (url == null) return null;

// If configured, don't follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;

// Most redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
}
if (!maintainBody) {
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
}

// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}

return requestBuilder.url(url).build();

case HTTP_CLIENT_TIMEOUT:
// 408's are rare in practice, but some servers like HAProxy use this response code. The
// spec says that we may repeat the request without modifications. Modern browsers also
// repeat the request (even non-idempotent ones.)
if (!client.retryOnConnectionFailure()) {
// The application layer has directed us not to retry the request.
return null;
}

if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}

if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
// We attempted to retry and got another timeout. Give up.
return null;
}

if (retryAfter(userResponse, 0) > 0) {
return null;
}

return userResponse.request();

case HTTP_UNAVAILABLE:
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
// We attempted to retry and got another timeout. Give up.
return null;
}

if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
// specifically received an instruction to retry without delay
return userResponse.request();
}

return null;

default:
return null;
}
}
```
不难看出, 是根据响应码进行判断的。
- HTTP_PROXY_AUTH 407 代理身份验证
- HTTP_UNAUTHORIZED 401 未授权
- HTTP_PERM_REDIRECT 308 重定向
- HTTP_TEMP_REDIRECT 307 重定向
- HTTP_MULT_CHOICE 300 Multiple Choices
- HTTP_MOVED_PERM 301 Moved Permanently
- HTTP_MOVED_TEMP 302 Temporary Redirect
- HTTP_SEE_OTHER 303 See Other
- HTTP_CLIENT_TIMEOUT 408 Request Time-Out
- HTTP_UNAVAILABLE 503 Service Unavailable

对于这些响应码都做了处理:
1.返回null
```
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
```
2.其他异常情况直接抛异常了

强调:
`MAX_FOLLOW_UPS`字段, 表示最大的重定向次数
```
/**
* How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
* curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
*/
private static final int MAX_FOLLOW_UPS = 20;
```

```
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
```
这节就说到这,希望对大家有所帮助.....
![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084746645-654895211.png)

大家可以关注我的微信公众号:「秦子帅」一个有质量、有态度的公众号!

![公众号](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084746832-730035128.jpg)

Okhttp3源码解析(5)-拦截器RetryAndFollowUpInterceptor的更多相关文章

  1. Okhttp3源码解析(4)-拦截器与设计模式

    ### 前言 回顾: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析](htt ...

  2. 源码解析Grpc拦截器(C#版本)

    前言 其实Grpc拦截器是我以前研究过,但是我看网上相关C#版本的源码解析相对少一点,所以笔者借这篇文章给大家分享下Grpc拦截器的实现,废话不多说,直接开讲(Grpc的源码看着很方便,包自动都能还原 ...

  3. axios源码解析 - 请求拦截器

    axios请求拦截器,也就是在请求发送之前执行自定义的函数. axios源码版本 - ^0.27.2 (源码是精简版) 平时在业务中会这样去写请求拦截器,代码如下: // 创建一个新的实例 var s ...

  4. axios 源码解析(下) 拦截器的详解

    axios的除了初始化配置外,其它有用的应该就是拦截器了,拦截器分为请求拦截器和响应拦截器两种: 请求拦截器    ;在请求发送前进行一些操作,例如在每个请求体里加上token,统一做了处理如果以后要 ...

  5. Okhttp3源码解析(3)-Call分析(整体流程)

    ### 前言 前面我们讲了 [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析]( ...

  6. springMVC源码分析之拦截器

    一个东西用久了,自然就会从仅使用的层面上升到探究其原理的层面,在javaweb中springmvc更是如此,越是优秀的框架,其底层实现代码更是复杂,而在我看来,一个优秀程序猿就相当于一名武林高手,不断 ...

  7. springMVC源码分析--HandlerInterceptor拦截器调用过程(二)

    在上一篇博客springMVC源码分析--HandlerInterceptor拦截器(一)中我们介绍了HandlerInterceptor拦截器相关的内容,了解到了HandlerInterceptor ...

  8. Okhttp3源码解析(2)-Request分析

    ### 前言 前面我们讲了 [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析]( ...

  9. SpringMVC源码阅读:拦截器

    1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...

随机推荐

  1. C#5.0新增功能02 调用方信息

    连载目录    [已更新最新开发文章,点击查看详细] 通过使用调用方信息特性,可获取有关方法的调用方的信息. 可以获取源代码的文件路径.源代码中的行号和调用方的成员名称. 此信息有助于跟踪.调试和创建 ...

  2. 使用nginx+tomcat实现动静分离

    动态资源与静态资源的区别 微微的概括一下 静态资源: 当用户多次访问这个资源,资源的源代码永远不会改变的资源. 动态资源:当用户多次访问这个资源,资源的源代码可能会发送改变. 什么是动静分离 动静分离 ...

  3. 牛客第三场 J LRU management

    起初看到这道题的时候,草草就放过去了,开了另一道题,结果开题不顺利,总是感觉差一点就可以做出来,以至于一直到最后都没能看这道题qaq 题意:类似于操作系统上讲的LRU算法,有两个操作,0操作代表访问其 ...

  4. Redis项目实战---应用及理论(二)---Redis集群原理

    一. Redis官方推荐集群方案:Redis Cluster 适用于redis3.0以后版本,        redis cluster 是redis官方提供的分布式解决方案,在3.0版本后推出的,有 ...

  5. IntelliJ IDEA 2019.2最新解读:性能更好,体验更优,细节处理更完美!

    idea 2019.2 准备 idea 2019.2正式版是在2019年7月24号发布的,本篇文章,我将根据官方博客以及自己的理解来进行说明,总体就是:性能更好,体验更优,细节处理更完美! 支持jdk ...

  6. 在 alpine 中使用 NPOI

    在 alpine 中使用 NPOI Intro 在 .net 中常使用 NPOI 来做 Excel 的导入导出,NPOI 从 2.4.0 版本开始支持 .netstandard2.0,对于.net c ...

  7. java遍历所有目录和文件

    package xian; import java.io.File; import java.util.ArrayList; public class GetFile { private static ...

  8. python中的赋值操作与C语言中的赋值操作中的巨大差别

    首先让我们来看一个简单的C程序: a = ; b = a; b = ; printf("a = %d, b = %d\n", a, b); 相信只要学过C语言, 不用运行程序便能知 ...

  9. 手机APP测试之Fiddler

    之前测试基本上是web端,突然接手了一个要在指定pad上测试APP的任务,于是决定研究研究pad抓包.最开始考虑有jmeter进行抓包测试,发现抓不到(可能方法有问题,后续还需继续研究),然后用fid ...

  10. grep使用集合

    一.grep使用 (一).选项 -a 不要忽略二进制数据. -A<显示列数> 除了显示符合范本样式的那一行之外,并显示该行之后的内容. -b 在显示符合范本样式的那一行之外,并显示该行之前 ...