核心功能
1.连接失败重试(Retry)
在发生 RouteException 或者 IOException 后,会捕获建联或者读取的一些异常,根据一定的策略判断是否是可恢复的,如果可恢复会重新创建 StreamAllocation 开始新的一轮请求
2.继续发起请求(Follow up)
主要有这几种类型
3xx 重定向
401,407 未授权,调用 Authenticator 进行授权后继续发起新的请求
408 客户端请求超时,如果 Request 的请求体没有被 UnrepeatableRequestBody 标记,会继续发起新的请求
其中 Follow up 的次数受到MAX_FOLLOW_UP 约束,在 OkHttp 中为 20 次,这样可以防止重定向死循环
流程图
image.png源码分析
@Override public Response intercept(Chain chain) throws IOException {
// 1. 获取 Transmitter对象
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Transmitter transmitter = realChain.transmitter();
int followUpCount = 0;
Response priorResponse = null;
while (true) {
transmitter.prepareToConnect(request);
if (transmitter.isCanceled()) {
throw new IOException("Canceled");
}
Response response;
boolean success = false;
try {
// 2. 执行下一个拦截器,即BridgeInterceptor
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
// 3. 如果有异常,判断是否要恢复
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.
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.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Exchange exchange = Internal.instance.exchange(response);
Route route = exchange != null ? exchange.connection().route() : null;
// 检查是否符合重定向要求
Request followUp = followUpRequest(response, route);
if (followUp == null) {
if (exchange != null && exchange.isDuplex()) {
transmitter.timeoutEarlyExit();
}
// 返回结果
return response;
}
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
// 5.关闭响应流
closeQuietly(response.body());
if (transmitter.hasExchange()) {
exchange.detachWithViolence();
}
//最大限制判断
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
request = followUp;
priorResponse = response;
}
}
这就是RetryAndFollowUpInterceptor的核心代码 我们来一步步的分析
1.获取一个Transmitter 对象
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Transmitter transmitter = realChain.transmitter();
他是网络请求的调度器,作用在整个网络请求生命周期 它用于协调Connection,Stream,Call。他的创建是在newRealCall的时候
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
// Safely publish the Call instance to the EventListener.
RealCall call = new RealCall(client, originalRequest, forWebSocket);
call.transmitter = new Transmitter(client, call);
return call;
}
2.开启循环,执行下一个调用链(拦截器),等待返回结果(Response)
response = realChain.proceed(request, streamAllocation, null, null);
3.如果catch了进入recover 判断收可以重新请求
private boolean recover(IOException e, Transmitter transmitter,
boolean requestSendStarted, Request userRequest) {
// The application layer has forbidden retries.
//如果OkHttpClient直接配置拒绝失败重连,return false
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;
}
无法重试的isRecoverable()原因
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;
}
4.关闭响应流
closeQuietly(response.body());
5.增加重定向次数
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
```、
6.继续循环知道返回response或者 抛出异常
到这里RetryAndFollowUpInterceptor的分析就结束了进入下一个。
最后献上一份添加了注释的源码 [https://github.com/525642022/okhttpTest/blob/master/README.md](https://github.com/525642022/okhttpTest/blob/master/README.md)
哈哈
网友评论