okhttp封装了具有重试、重定向功能的拦截器RetryAndFollowUpInterceptor,它是okhttp自带的第一层拦截器。
下面分析它的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.
//路由连接异常,判断能否重试,无法重试抛出异常,否则continue
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.
//正常情况此时releaseConnection=false。如遇异常且无法重试,释放资源
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
//保存重定向前的响应,第一次循环priorResponse=null
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//判断是否需要重定向。如果需要,会对request做一些修改,返回新的request;否则返回null
Request followUp = followUpRequest(response);
if (followUp == null) {
//无重定向,释放资源,直接返回reponse给上层
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
//释放此response的body中开启的字节流
closeQuietly(response.body());
//判断次数是否超过上限20次
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
//request的body通常情况下不为UnrepeatableRequestBody
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
if (!sameConnection(response, followUp.url())) {
//比较重定向前后接口地址scheme、host、port是否一致,一致的话可重用,否则释放资源重新创建
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;
}
}
1.StreamAllocation对象
StreamAllocation主要用来管理Connections/Streams的资源分配和释放,这里主要用它来释放资源。在底层的拦截器中会更深入的使用StreamAllocation,后面再具体分析。
2.recover方法
在try-catch中执行chain.proceed方法,如果捕获到RouteException和IOException异常,就会调用recover方法判断该请求能否重试。
private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);
// The application layer has forbidden retries.
//retryOnConnectionFailure默认返回true(在构建OkHttpClient时,可通过retryOnConnectionFailure方法设置)
if (!client.retryOnConnectionFailure()) return false;
// We can't send the request body again.
//当捕获到的异常是RouteException和ConnectionShutdownException(继承自IOException)时requestSendStarted为false,其他情况为true;request的body通常情况下不为UnrepeatableRequestBody
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;
}
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;
}
- ProtocolException 协议异常不可重试
- 捕获到RouteException,传入RouteException的getLastConnectException,若lastException为SocketTimeoutException可重试,否则不可重试。即出现连接超时,可尝试下一个路由重试
- SSLHandshakeException ssl握手异常,若是由来自X509TrustManager的CertificateException引起则不可重试
- SSLPeerUnverifiedException ssl证书校验异常不可重试
3.followUpRequest方法
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;
// 从header中取出Location值,它就是重定向地址
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.
// 判断请求方式,将除了PROPFIND的重定向请求转为GET请求。请求方式若为PROPFIND,则保持原来的method和requestBody,否则method设为GET且丢弃requestBody。
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) {
//请求方式不为PROPFIND,移除以下三个属性
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.
// 若重定向地址和原来的地址scheme、host、port一致,则移除身份验证请求头
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;
}
// 如果经历过重定向,且上一轮状态码是同样的HTTP_CLIENT_TIMEOUT,则放弃
if (userResponse.priorResponse() != null
&& userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
// We attempted to retry and got another timeout. Give up.
return null;
}
return userResponse.request();
default:
return null;
}
}
followUpRequest方法内部会判断服务端返回的状态码来决定是否重定向,若返回新的request表示需要重定向,返回null表示不进行重定向。
三种情况下会重新发起请求:
1. HTTP_PROXY_AUTH(407)、HTTP_UNAUTHORIZED(401),返回包含证书信息的request重新请求进行认证。
2. HTTP_MULT_CHOICE(300)、HTTP_MOVED_PERM(301)、HTTP_MOVED_TEMP(302)、HTTP_SEE_OTHER(303),修改request的method、url等参数,返回进行重定向。
3. HTTP_CLIENT_TIMEOUT(408),请求超时,直接返回request进行重试。
总结
RetryAndFollowUpInterceptor的intercept中先是创建了StreamAllocation对象,然后开启while(true)无限循环。接着在这个循环中先调用下层拦截器去网络请求,若请求期间发生异常,判断能否重试,能就continue进行下一轮循环,否则抛异常退出循环结束方法。如果下层拦截器请求完成返回response,通过response的状态码判断是否需要重定向,若需要重定向,修改request后进行下一轮循环,否则返回response结束方法。