本篇讲解OKhttp的拦截器链,拦截器是OKhttp最大特色之一,通过拦截器链,可以拦截到请求数据或响应数据并对它们进行相关处理,我们还可以自定义拦截器interceptor
上篇文章中我们讲到,不管是OKhttp的同步请求还是异步请求,最后都会调用getResponseWithInterceptorChain来完成请求,那么本篇文章就从这个方法开始,来分析OKhttp的拦截器链策略的实现
Response getResponseWithInterceptorChain() throws IOException {
//保存拦截器的集合
List<Interceptor> interceptors = new ArrayList<>();
//添加自定义的拦截器
interceptors.addAll(client.interceptors());
//添加处理网络请求失败的拦截器
interceptors.add(retryAndFollowUpInterceptor);
//添加处理请求头和响应头的拦截器
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//添加负责缓存管理的拦截器
interceptors.add(new CacheInterceptor(client.internalCache()));
//添加负责和服务器建立连接的拦截器
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
//添加网络拦截器,网络拦截器可以记录被重定向的请求
interceptors.addAll(client.networkInterceptors());
}
//添加发送请求数据和读取响应数据的拦截器
interceptors.add(new CallServerInterceptor(forWebSocket));
//创建第一个拦截器链节点
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
//开始第一个链节点的执行
return chain.proceed(originalRequest);
}
之前我们知道,每个请求都是通过拦截器链策略来完成整个请求过程的,所以说OKhttp的请求是放在一个链条上去一步一步完成的,至于这个链条的执行机制是怎么样的,我们现在可以先猜想。形象来说,链条上有很多链节点,每个链节点都有自己的执行任务,一个请求任务从链条的头节点开始传递,先后经过每一个节点,然后每个节点都从上一个节点接收到任务并进行处理之,再传递给下一个节点,就这样最终完成了整个请求任务,我想所谓的拦截器链策略就是这样的吧
上面的getResponseWithInterceptorChain方法是一个任务的拦截器的开始,首先添加自定义的拦截器和框架内置的拦截器,然后是初始化第一个拦截器链节点,这个chain节点可以是说整条拦截器链的开始了,然后通过它的proceed方法,开始第一个链节点的执行,从而开启了整个拦截器链的任务执行之旅,以下来看看关键的proceed方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
//创建下一个的拦截器链节点,其中index加1,代表下一个链节点中轮流到拦截器集合interceptores
//中的第index+1个拦截器执行任务了
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
//获取index对应的拦截器
Interceptor interceptor = interceptors.get(index);
//执行拦截器的intercept方法,传参下一个拦截器链节点,可以猜想的时候,在拦截器的
//intercept方法中肯定会执行next的proceed方法
Response response = interceptor.intercept(next);
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
if (response.body() == null) {
throw new IllegalStateException(
"interceptor " + interceptor + " returned a response with no body");
}
return response;
}
在链节点的proceed方法中,首先通过参数index取出拦截器集合中对应的拦截器对象,有没有注意到在创建第一个拦截器链节点时候,第四个参数传递的其实就是这个index值,当时我们传递的是0,所以此时取出的是拦截器集合中的第一个拦截器实例;代码读到这里,我们可以这么理解,拦截器链中的每一个链节点都会取出一个对应的拦截器来执行相关任务,比如这里是第一个链节点,那么取出的当然也就是第一个拦截器了
在执行拦截器的intercept方法前,我们会创建下一个链节点实例,注意到此时第四个参数传递index+1,代表下一个链节点执行的是第index+1个拦截器的任务,然后调用当前拦截器的intercept方法,传参下一个链节点next,通常我们都会在intercept方法中获取请求或者响应数据并进行相关处理,在intercept方法会调用下一个链节点的proceed方法,proceed方法又重复上面的执行逻辑
仔细分析整个拦截器链的执行逻辑,每个链节点都会生成一个下一个节点,并执行当前拦截器的intercept方法,然后返回当前拦截器处理结果response,这里面其实形成一个递归的逻辑了,那么这个递归的结束条件是什么呢?那肯定就是最后一个链节点了,最后一个链节点中执行的最后一个拦截器的任务,从最开始添加拦截器集合的顺序来看,最开始是添加自定义拦截器,最后添加的拦截器是CallServerInterceptor,这是底层负责网络请求的拦截器,所以最后一个链节点将不再执行下一个节点的proceed方法,而是直接返回网络请求的结果给上一个链节点,这样数据又从拦截器链的最后一个节点回来了
如图所示:
这个图画得不是很好,不过也大概就是这个意思吧,像这种设计模式在业内叫责任链模式,跟Android中View的事件分发机制一样,View的事件分发也是采用责任链模式,所谓的责任链模式,顾名思义,就是处理相关事务的过程形成一条执行链,执行链上有多个节点,每个节点都有机会处理请求事务,如果某个节点处理完了就可以根据实际业务需求传递给下一个节点继续处理或者处理完毕返回
从上面的分析中我们懂得了OKhttp的连接器链的执行策略,下面来看一下框架内置的那几个拦截器里面都干了什么
1.RetryAndFollowUpInterceptor
RetryAndFollowUpInterceptor主要负责请求失败重试,来看它的intercept方法
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//执行下一个链节点的proceed方法
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.getLastConnectException();
}
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();
}
}
...
request = followUp;
priorResponse = response;
}
}
一般来说一个拦截器的逻辑大致分为三部分:
1.发起请求前对request进行处理
2.调用下一个链节点的proceed方法获得相应结果response
3.对response进行处理,并返回给上一个拦截器链节点
这里暂且不去分析里面的逻辑,涉及的范围有点复杂,因为StreamAllocation涉及到连接池的内容,我们后面再分析这个内容,但在这里可以看到的是,里面确实执行了下一个链节点的proceed方法,只有执行了这个方法,任务才能继续传递给下一个链节点去处理
2.BridgeInterceptor
BridgeInterceptor拦截器的主要作用:
1.设置请求头内容类型、长度、编码
2.添加cookie
3.设置其他报头,如User-Agent,Host,Keep-alive等,其中Keep-Alive是实现多路复用的必要步骤
4.设置gzip压缩,并在接收到内容后进行解压,省去了应用层处理数据解压的麻烦
@Override public Response intercept(Chain chain) throws IOException {
//获取请求数据
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//设置类型、长度、编码
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
//设置host、Keep-alive等
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
//设置cookie
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
//执行下一个链节点并返回响应结果response
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
//判断是否支持gzip压缩格式,
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
//交给okio处理,然后生成一个新的response
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
3.CacheInterceptor
CacheInterceptor拦截器主要负责数据缓存的相关处理
1.当请求有符合要求的cache时直接返回cache
2.当服务器返回内容有更改时则更新cache
@Override public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
// If we don't need the network, we're done.
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
Response networkResponse = null;
try {
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
关于OKhttp的缓存管理,这个模块的内容比较多,所以这里先不作分析,后面会专门写一篇文章来讲解
4.ConnectInterceptor
此拦截器负责获取连接
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
//获取合适的连接
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
上边的关键代码是RealConnection connection = streamAllocation.connection(),通过连接池获取到一个合适的连接,可能复用已有的连接也可能创建新的连接,具体由连接池决定,关于连接池的内容后面也会专门写一篇文章来讲解
5.CallServerInterceptor
CallServerInterceptor拦截器是负责向服务器发起真正的网络请求,并接收到服务器响应以后返回请求结果
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
HttpCodec httpCodec = realChain.httpStream();
StreamAllocation streamAllocation = realChain.streamAllocation();
RealConnection connection = (RealConnection) realChain.connection();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
realChain.eventListener().requestHeadersStart(realChain.call());
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
// If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
// Continue" response before transmitting the request body. If we don't get that, return
// what we did get (such as a 4xx response) without ever transmitting the request body.
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(true);
}
if (responseBuilder == null) {
// Write the request body if the "Expect: 100-continue" expectation was met.
realChain.eventListener().requestBodyStart(realChain.call());
long contentLength = request.body().contentLength();
CountingSink requestBodyOut =
new CountingSink(httpCodec.createRequestBody(request, contentLength));
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
realChain.eventListener()
.requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
} else if (!connection.isMultiplexed()) {
// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
// from being reused. Otherwise we're still obligated to transmit the request body to
// leave the connection in a consistent state.
streamAllocation.noNewStreams();
}
}
httpCodec.finishRequest();
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
int code = response.code();
if (code == 100) {
// server sent a 100-continue even though we did not request one.
// try again to read the actual response
responseBuilder = httpCodec.readResponseHeaders(false);
response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
response = response.newBuilder()
.body(httpCodec.openResponseBody(response))
.build();
}
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
streamAllocation.noNewStreams();
}
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
因为CallServerInterceptor是拦截器链中的最后一个拦截器,所以这将不再执行下一个链节点的proceed方法,而是直接返回网络请求的结果,这也是这条拦截器链中递归执行的返回条件,至于这个拦截器中的内容,我们后面的文章涉及的时候再讲解可能会比较好理解
上面我们整体分析了OKhttp拦截器链策略机制和几个内置拦截器的主要作用,拦截器链是OKhttp的核心,它贯穿了框架的整个网络请求过程,下面是一个整体的流程图:
关于拦截器链的内容就讲到这里吧,下篇讲OKhttp的缓存管理