版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangshuaionline/article/details/89031298
功能:重试与重定向拦截器。
由于是工厂方法模式,直接调用intercept方法
@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) {
//创建流
transmitter.prepareToConnect(request);
...
Response response;
boolean success = false;
try {
//交给下一个拦截起处理
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
...
continue;
}...
...
//根据异常状态,返回request对象(判断网络状态404...)
Request followUp = followUpRequest(response, route);
//如果为null(没有异常)关闭请求
if (followUp == null) {
...
return response;
}
//如果body不是空,并且设置了最多可以传输一次,返回response
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
//关闭已有的请求
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;
}
}
特点:
- 通过while(true)死循环来进行重新连接
- 通过响应码来决定下一次循环的行为是重试、重定向。。。