说明
OKHTTP内部存在诸多拦截器分别负责不同的功能,其中OKHTTP内部RetryAndFollowUpInterceptor 主要负责请求的重试机制,今天我们来看下OKHttp是如何实现重试机制的;
首先看下怎么开启或者关闭默认的重试机制;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true);
复制代码
重试机制默认是开启的。
源码解析
RetryAndFollowUpInterceptor重试机制关键代码如下:
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Transmitter transmitter = realChain.transmitter();
int followUpCount = 0;
Response priorResponse = null;
while (true) {
// 1. 首先尝试去创建一个请求流,准备链接
transmitter.prepareToConnect(request);
if (transmitter.isCanceled()) {
throw new IOException("Canceled");
}
Response response;
boolean success = false;
try {
//2. 开始执行,进入后续拦截器,真正进行网络请求;
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
// 3. 发生RouteException:路由链接异常的场景,请求不会被发送,抛出首次链接异常
if (!recover(e.getLastConnectException(), transmitter, false, request)) {
throw e.getFirstConnectException();
}
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
// 4. 发生IOException异常,是否可恢复判断逻辑参照上述RouteException判断逻辑
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, transmitter, requestSendStarted, request)) throw e;
continue;
} finally {
// The network call threw an exception. Release any resources.
if (!success) {
transmitter.exchangeDoneDueToException();
}
}
// Attach the prior response if it exists. Such responses never have a body.
//5. 根据上一个Response结果构建一个新的response对象,且这个对象的body为空
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//6. 根据请求码创建一个新的请求,以供下一次重试请求使用
Exchange exchange = Internal.instance.exchange(response);
Route route = exchange != null ? exchange.connection().route() : null;
Request followUp = followUpRequest(response, route);
//7. 如果第六步构建的出来的Request为空,则不再进行,直接返回Response
if (followUp == null) {
if (exchange != null && exchange.isDuplex()) {
transmitter.timeoutEarlyExit();
}
return response;
}
//8. 构建的Request对象出存在请求body且为一次性请求,则直接返回Response,也不进行重试。
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
closeQuietly(response.body());
if (transmitter.hasExchange()) {
exchange.detachWithViolence();
}
// 9. 判断当前重试次数是否已经到达最大次数(默认20),如果到达,则直接抛出异常
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
//10. 如果上述没有抛出异常或者中断循环,则进入while循环,开始下一次重试过程
request = followUp;
priorResponse = response;
}
}
复制代码
1. 首先尝试去创建一个请求流,准备链接;
2. 开始执行,进入后续拦截器,真正进行网络请求;
3. 发生RouteException:路由链接出现异常,且多次重试后没有一次正常;然后判断当前路由异常是否可恢复,不可恢复的时候抛出FirstConnectException,可恢复则进行充实,具体判断逻辑如下:
/**
* 是否可恢复
*/
private boolean recover(IOException e, Transmitter transmitter,
boolean requestSendStarted, Request userRequest) {
// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false;
// We can't send the request body again.
if (requestSendStarted && requestIsOneShot(e, userRequest)) return false;
// This exception is fatal.
if (!isRecoverable(e, requestSendStarted)) return false;
// No more routes to attempt.
if (!transmitter.canRetry()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
private boolean requestIsOneShot(IOException e, Request userRequest) {
RequestBody requestBody = userRequest.body();
return (requestBody != null && requestBody.isOneShot())
|| e instanceof FileNotFoundException;
}
private boolean isRecoverable(IOException e, boolean requestSendStarted) {
// 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 && !requestSendStarted;
}
// 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;
}
复制代码
上述代码逻辑如下:
1. 首先判断是否允许重试,根据我们创建请求的时候配置的重试开关,则不允许重试;
2. 第二层判断如果请求已经开始,且当前请求最多只能被发送一次的情况下,则不允许重试;
3. 判断当前请求是否可恢复的,以下异常场景不可恢复:
a. ProtocolException,协议异常
b. SocketTimeoutException,Socket链接超时且请求没有开始
c. SSLHandshakeException && CertificateException :
表示和服务端约定的安全级别不匹配异常,引起基本为证书引起的,这种链接是不可用的。
d. SSLPeerUnverifiedException
对等实体认证异常,也就是说对等个体没有被验证,类似没有证书,
或者在握手期间没有建立对等个体验证;
4. 判断是否存在其他可重试的路由,如果不存在,不允许重试;
5. 不属于上述情况判断可以重试;
复制代码
4. 发生IOException异常,是否可恢复判断逻辑参照上述RouteException判断逻辑;
5. 根据上一个Response结果构建一个新的response对象,且这个对象的body为空;
6. 根据请求码创建一个新的请求,以供下一次重试请求使用:会根据上一次的请求结果添加认证头信息,跟踪重定向或处理客户端请求超时等。
代码如下:
private Request followUpRequest(Response userResponse, @Nullable 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.request().url(), 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;
}
RequestBody requestBody = userResponse.request().body();
if (requestBody != null && requestBody.isOneShot()) {
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;
}
}
复制代码
会根据结果码返回不同的Request对象(返回空表示当前的请求跟踪是没有必要的,或者可应用的):
-
HTTP_PROXY_AUTH(407):代理认证,需要进行代理认证(默认实现返回null,可以进行重写覆盖实现);
-
HTTP_UNAUTHORIZED(401):未授权,需要进行授权认证(默认实现返回null,可以进行重写覆盖实现);
-
HTTP_PERM_REDIRECT(307) 或者 HTTP_TEMP_REDIRECT(308) :临时重定向或者永久重定向,如果请求方法不为GET且不为METHOD,返回空,表示不允许重定向;
-
HTTP_MULT_CHOICE(300) 多选项
HTTP_MOVED_PERM(301) 永久重定向,表示请求的资源已经分配了新的URI,以后应该使用新的URI
HTTP_MOVED_TEMP(302)临时性重定向,
HTTP_MOVED_TEMP(303)表示由于请求对应的资源存在着另外一个URI,应该使用GET方法定向获取请求的资源这四种code对应的逻辑为:
- 首先判断是否允许重定向,不允许返回空;
- 然后判断结果里面locations头,是否可以解析,不可正常解析返回空;
- 结果返回scheme和请求的scheme不一致且不允许ssl重定向,返会空;
- 针对存在请求body的,如果可以重定向为GET,则构建GET请求,否则构建原有请求;
- 跨主机重定向时,删除所有身份验证头。
- 最后构建请求Request对象。
-
HTTP_CLIENT_TIMEOUT(408):请求超时,逻辑如下
- 如果不允许重试,直接返回空
- 如果当前Response不为空,且只允许请求一次,则直接返回空
- 本次请求结果和上一次请求结果均超时,则放弃重试
- 解析结果相应头Retry-After(响应的 HTTP 报头指示所述用户代理应该多长时间使一个后续请求之前等待):
如果当前Retry-After大于0,则返回空;
-
HTTP_UNAVAILABLE(503):表明服务器暂时处于超负载或正在进行停机维护,现无法处理请求。
- 本次请求结果和上一次请求结果均返回503,则放弃重试
- 如果返回的Retry-After为0,没有任何延迟,则返回Request对象,否则返回空;
7. 如果第六步构建的出来的Request为空,则不再进行,直接返回Response
8. 构建的Request对象出存在请求body且为一次性请求,则直接返回Response,也不进行重试。
9. 最后判断当前重试次数是否已经到达最大次数(默认20),如果到达,则直接抛出异常。
10. 如果上述没有抛出异常或者中断循环,则进入while循环,开始下一次重试过程。
到此,重试机制RetryAndFollowUpInterceptor 分析结束。