OkHttp3源码(九) ------ 拦截器

拦截器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(……)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值