OkHttp拦截器链源码解读传送门:https://www.jianshu.com/p/1181f48d6dcf
RetryAndFollowUpInterceptor这个类在OkHttp请求当中充当重定向及重试拦截的角色;
/**
* This interceptor recovers from failures and follows redirects as necessary. It may throw an
* {@link IOException} if the call was canceled.
* 重定向和网络请求失败重试的拦截器,上面注释中说到如果取消会引起IO流异常
*/
public final class RetryAndFollowUpInterceptor implements Interceptor {
/**
* 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; // 失败的网络请求重连最大次数
private final OkHttpClient client;
private final boolean forWebSocket; // 是否使用WebSocket进行拦截
private volatile StreamAllocation streamAllocation; // 建立创建Http请求的一些网络组件
private Object callStackTrace;
private volatile boolean canceled;
public RetryAndFollowUpInterceptor(OkHttpClient client, boolean forWebSocket) {
this.client = client;
this.forWebSocket = forWebSocket;
}
// 拦截进行重定向
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
// 建立创建Http请求的一些网络组建
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
// 重定向次数
int followUpCount = 0;
Response priorResponse = null;
// 将前一步得到的followUp 赋值给request,重新进入循环
while (true) {
if (canceled) {
streamAllocation.release(); // 把连接上的call请求释放掉
throw new IOException("Canceled"); // 抛出取消Io流异常
}
Response response;
boolean releaseConnection = true;
try {
// proceed 内部会实现下一个拦截器链的方法 这个在上一篇已经分析过了
// 将前一步得到的followUp不为空进入循环 继续执行下一步 followUp就是request
// 继续执行下一个Interceptor,即BridgeInterceptor
// 进行重定向进行新的请求
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.
// 构建响应体,这个响应体的body为空
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Request followUp;
try {
// 根据响应码处理请求,返回Request不为空时则进行重定向处理,拿到重定向的request
followUp = followUpRequest(response, streamAllocation.route());
} catch (IOException e) {
streamAllocation.release();
throw e;
}
// followUp 就是followUpRequest方法经过检测返回的Request
if (followUp == null) {
streamAllocation.release();
return response; // 如果Request为空 则return response;
} else {
// 如果Request不为空 则再次进入 while (true) 重新执行
}
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; // 把重定向的请求赋值给request,以便再次进入循环执行
priorResponse = response;
}
}
重定向功能的逻辑在followUpRequest方法,followUpRequest会拿到重定向的request
/**
* Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
* either add authentication headers, follow redirects or handle a client request timeout. If a
* follow-up is either unnecessary or not applicable, this returns null.
*
* 计算出HTTP请求响应收到的userResponse响应。
*
* 这将添加身份验证标头,遵循重定向或处理客户端请求超时。
*
* 如果后续措施不必要或不适用,则返回null。
*/
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: // 407 代理认证
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: // 401 未经认证
return client.authenticator().authenticate(route, userResponse);
case HTTP_PERM_REDIRECT: // 308
case HTTP_TEMP_REDIRECT: // 307 临时重定向
// "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"
// 如果接收到307或308状态码以响应除GET或HEAD以外的请求,则用户代理绝不能自动重定向请求
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE: // 300 多种选择
case HTTP_MOVED_PERM: // 301 永久移动到新的Url
case HTTP_MOVED_TEMP: // 302 暂时重定向
case HTTP_SEE_OTHER: // 303 查看其他地址和301有点类似
// 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.
// url为null,不允许重定向
if (url == null) return null;
// If configured, don't follow redirects between SSL and non-SSL.
// 查询是否存在http与https之间的重定向
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 超时
// 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()) { // 这里就可以看出,在创建调用OkHttp的时候可以设置不进行重定向
// 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: // 503 服务不可用
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;
}
}
从上面可以看出重定向功能默认是开启的,可以选择关闭,然后去实现自己的重定向功能
new OkHttpClient.Builder()
.followRedirects(false) //禁制OkHttp的重定向操作,我们自己处理重定向
.followSslRedirects(false)//https的重定向也自己处理
总结一下重定向拦截器的流程:
1.构建一个StreamAllocation对象
2.调用RealInterceptorChain.proceed(.....)进行网络请求
3.根据异常结果或者响应结果判断是否要进行重新请求
4.调用下一个拦截器,即BridgeInterceptor,对response进行处理,返回给上一个拦截器
PS:抛出异常,在以下情况下是不会重试的
- 客户端配置出错不再重试,因为出错后,request body不能再次发送
- ProtocolException:协议异常
- InterruptedIOException:中断异常
- SSLHandshakeException:SSL握手异常
- SSLPeerUnverifiedException:SSL握手未授权异常
- 没有更多线路可以选择
7.根据响应码处理请求,返回Request不为空时则进行重定向处理,重定向的次数超过20次,因为在这个一开始成员变量中做了限制,失败的网络请求重连最大次数是20。
上面还用到了一个类StreamAllocation,它维护了Connections、Streams和Calls之间的管理,该类初始化一个Socket连接对象,获取输入/输出流对象。但是你会发现StreamAllocation在RetryAndFollowUpInterceptor只做了一些取消、释放资源等操作,并没有真正的去执行网络连接,这是因为这一步操作是在拦截器ConnectInterceptor中使用,所以这里先不去详细阅读,等分析到ConnectInterceptor拦截器的时候在深入阅读。
谢谢阅读,如有错误,欢迎指正。
OkHttp的桥拦截器的源码解读传送门:https://www.jianshu.com/p/20bfab62c3cd
网友评论