拦截器Interceptor的设计思想——创建拦截器链(后面简称链),执行指定拦截器的方法,根据旧链创建新链,再次执行上述过程,直至全部拦截器执行完毕。
拦截器方法(intercept(…))的主要实现:
(1)、对发起的request进行处理。
(2)、调用下一个拦截器,获取response。
(3)、对上一个拦截器返回的response进行处理,最后返回给上个拦截器。
.
OkHttp3执行网络请求及接受响应的过程中要经过
普通拦截器>RetryAndFollowUpInterceptor>BridgeInterceptor
.>CacheInterceptor>ConnectInterceptor>网络拦截器>CallServerInterceptor
接下来我们会按照如下顺序讲解拦截器的具体实现。
(1)、RetryAndFollowUpInterceptor
(2)、BridgeInterceptor
(3)、CacheInterceptor
(4)、ConnectInterceptor
(5)、CallServerInterceptor
(1)、RetryAndFollowUpInterceptor的intercept(…)
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
releaseConnection = false;
continue;
} catch (IOException e) {
releaseConnection = false;
continue;
} finally {
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Request followUp = followUpRequest(response);
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
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()), 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;
}
}
主要做了4件事:
1、为连接流配置连接池,以便后面为连接流“找”连接时提供“地方”。
2、将连接流交由下一个拦截器处理。
3、判断是否重连接。
4、返回响应报文。
(2)、BridgeInterceptor的intercept(……)