这一篇主要分析RetryAndFollowUpInterceptor这个过滤器,这个过滤器的职责是重试和重定向。通过前面一篇文章,我们知道一个过滤器的功能,重点都在他重写Interceptor的intercept(Chain chain)方法。下面是该拦截器的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);
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(), 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.
//这里基本上都没有讲,priorResponse是用来保存前一个Resposne的,这里可以看到将前一个Response和当前的Resposne
//结合在一起了,对应的场景是,当获得Resposne后,发现需要重定向,则将当前Resposne设置给priorResponse,再执行一遍流程,
//直到不需要重定向了,则将priorResponse和Resposne结合起来。
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//判断是否需要重定向,如果需要重定向则返回一个重定向的Request,没有则为null
Request followUp = followUpRequest(response);
if (followUp == null) {
//不需要重定向
if (!forWebSocket) {
//是WebSocket,释放
streamAllocation.release();
}
//返回response
return response;
}
//需要重定向,关闭响应流
closeQuietly(response.body());
//重定向次数++,并且小于最大重定向次数MAX_FOLLOW_UPS(20)
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
//是UnrepeatableRequestBody, 刚才看过也就是是流类型,没有被缓存,不能重定向
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
//判断是否相同,不然重新创建一个streamConnection
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, 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;
}
}
RetryAndFollowUpInterceptor 是 OKHTTP 内置中的第一个拦截器,其功能主要有以下几点:
1.创建 StreamAllocation 对象;
2.调用 RealInterceptorChain.proceed(...)进行网络请求;
3.根据异常结果或者响应结果判断是否要进行重新请求。
注意第二和第三点是在 while (true)内部执行的,也就是系统通过死循环来实现重连机制。下面阅读 OKHTTP 源码来看 RetryAndFollowUpInterceptor 内部是怎么实现以上 3 点功能的。
1、创建 StreamAllocation 对象
StreamAllocation 在 RetryAndFollowUpInterceptor 创建,它会在 ConnectInterceptor 中真正被使用到,主要就是用于获取连接服务端的 Connection 和用于进行跟服务端进行数据传输的输入输出流 HttpStream,具体的操作不是这篇博客的重点,只要了解它的作用的就行了。
2、网络请求
因为在 OKHTTP 中的拦截器的执行过程是一个递归的过程,也就是它内部会通过 RealInterceptorChain 这个类去负责将所有的拦截器进行串起来。只有所有的拦截器执行完毕之后,一个网络请求的响应 Response 才会被返回。
但是呢,在执行这个过程中,难免会出现一些问题,例如连接中断,握手失败或者服务器检测到未认证等,那么这个 resposne 的返回码就不是正常的 200 了,因此说这个 response 并不一定是可用的,或者说在请求过程就已经抛出异常了,例如超时异常等,那么 RetryAndFollowUpInterceptor 需要依据这些问题进行判断是否可以进行重新连接。
while(true){
try{
...
response = ((RealInterceptorChain) chain).proceed(request,
streamAllocation, null, null);
...
}catch(RouteException e){
//判断 RouteException 否可以重连
}catch(IOException e){
//判断 IOException 否可以重连
}finally{
//释放流
}
...
}
3、 网络请求异常的“重连机制”
public Response proceed(Request request, StreamAllocation
streamAllocation, HttpStream httpStream,Connection connection) throws IOException {
在上面已经介绍过了网络请求时通过 RealInterceptorChain#proceed 方法进行的,该方法的声明中抛出了 IOException ,表示在整个网络请求过程有可能出现 IOException,但是我们看了在 catch 中还有一个异常那就是 RouteException,下面是两个异常的继承结构:
IOException 它是编译时,需要在编译时期就要捕获或者抛出。
public class IOException extends Exception
RouteException 是运行时异常,不需要显示的去捕获或者抛出。
public final class RouteException extends RuntimeException
try {
//网络请求
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
//表示是否要释放连接,在 finally 中会使用到。
releaseConnection = false;
} catch (RouteException e) {
//路由异常RouteException
// The attempt to connect via a route failed. The request will not have been sent.
//检测路由异常是否能重新连接
if (!recover(e.getLastConnectException(), true, request)) throw e.getLastConnectException();
//可以重新连接,那么就不要释放连接
releaseConnection = false;
//重新进行while循环,进行网络请求
continue;
} catch (IOException e) {
//检测该IO异常是否能重新连接
// An attempt to communicate with a server failed. The request may have been sent.
if (!recover(e, false, request)) throw e;
//可以重新连接,那么就不要释放连接
releaseConnection = false;
//重新进行while循环,进行网络请求
continue;
} finally {
//当 releaseConnection 为true时表示需要释放连接了。
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
3.1、RouteException 异常的重连机制
在 RouteException 的重连机制主要做了这样几件事:
通过 recover 方法检测该 RouteException 是否能重新连接;
可以重新连接,那么就不要释放连接 releaseConnection = false;
continue进入下一次循环,进行网络请求;
不可以重新连接就直接走 finally 代码块释放连接。
下面是通过 find Usages 得到 RouteException 被哪里抛出的图,从图可以看出 RouteException 是在获取一个 HttpStream 流和与 SOCKET 建立连接时出现异常才被抛出的,在抛异常的方法内部并没有显示地去捕获,因此异常会被 RetryAndFollowUpInterceptor#intercept 中的 catch 捕获,下面就是对捕获的异常的处理。
查看源码可以知道 RouteException 和 IOException 异常检测都会调用 recover 方法进行判断,主要是第二个参数不一样,这里传入的是true,表示该异常是 RouteException ,下面 IOException 检测时传入的参数时 false 。
if (!recover(e.getLastConnectException(), true, request)) throw
e.getLastConnectException();
3.2、 recover 方法异常检测
private boolean recover(IOException e, boolean routeException, Request userRequest) {
streamAllocation.streamFailed(e);
//1.判断 OkHttpClient 是否支持失败重连的机制
// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false;
// 在该方法中传入的 routeException值 为 true
// We can't send the request body again.
if (!routeException && userRequest.body() instanceof UnrepeatableRequestBody) return false;
//2.isRecoverable 检测该异常是否是致命的。
// This exception is fatal.
if (!isRecoverable(e, routeException)) return false;
// No more routes to attempt.
//3.是否有更多的路线
if (!streamAllocation.hasMoreRoutes()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
从上面源码可以看出 recover 方法主要做了以下几件事:
1.判断 OkHttpClient 是否支持失败重连的机制;
如果不支持重连,就表示请求失败就失败了,不能再重试了。
2.通过 isRecoverable 方法检测该异常是否是致命的;
3.是否有更多的路线,可以重试。
3.3、isRecoverable 方法异常检测
在该方法中会检测异常是否为严重异常,严重异常就不要进行重连了,下面检测的异常都做了注释。这里涉及到一个
SocketTimeoutException 的异常,表示连接超时异常,这个异常还是可以进行重连的,也就是说** OKHTTP 内部在连接超时时是会自动进行重连的。**
private boolean isRecoverable(IOException e, boolean routeException) {
//ProtocolException 这种异常属于严重异常,不能进行重新连接
// If there was a protocol problem, don't recover.
if (e instanceof ProtocolException) {
return false;
}
//当异常为中断异常时
// If there was an interruption don't recover, but if there was a timeout connecting to a route
// we should try the next route (if there is one).
if (e instanceof InterruptedIOException) {
return e instanceof SocketTimeoutException && routeException;
}
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different route.
//握手异常
if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry.
if (e.getCause() instanceof CertificateException) {
return false;
}
}
//验证异常
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
// An example of one we might want to retry with a different route is a problem connecting to a
// proxy and would manifest as a standard IOException. Unless it is one we know we should not
// retry, we return true and try a new route.
return true;
}
3.4、IOException 异常的重连机制
IOException 异常的检测实际上和 RouteException 是一样的,只是传入 recover 方法的第二个参数为 false 而已,表示该异常不是 RouteException ,这里就不分析了。
4、followUpRequest 响应码检测
当代码可以执行到 followUpRequest 方法就表示这个请求是成功的,但是服务器返回的状态码可能不是 200 ok 的情况,这时还需要对该请求进行检测,其主要就是通过返回码进行判断的。
private Request followUpRequest(Response userResponse) throws IOException {
if (userResponse == null) throw new IllegalStateException();
Connection connection = streamAllocation.connection();
Route route = connection != null
? connection.route()
: null;
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;
// Redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
requestBuilder.method(method, null);
}
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 (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
return userResponse.request();
default:
return null;
}
}
5、重试次数判断
在 RetryAndFollowUpInterceptor 内部有一个 MAX_FOLLOW_UPS 常量,它表示该请求可以重试多少次,在 OKHTTP 内部中是不能超过 20 次,如果超过 20 次,那么就不会再请求了。
private static final int MAX_FOLLOW_UPS = 20;
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}