getResponseWithInterceptorChain()
这个方法过,今天接着这部分继续,开始之前我们先预习一下——责任链模式。
ok,这个责任链模式是什么意思呢,首先“链”,就如我们生活中常见的锁链,一环扣一环,首尾相应,你想长点,就多接几圈,短点就少接几圈,对的,很灵活是吧,所以责任链模式的一大特征是灵活性。在咱们的编程世界里,每一个环就等于一个节点、一个对象,有各自负责的逻辑。当一个请求从链的首端发出,沿着链的路径依次传递给每一个节点,直到有节点处理这个请求为止,我们将这种模式称之为责任链模式。这种模式在筛选拦截方面的需求用处较多(比如咱们今天的okhttp)。第二个特征叫解耦,怎么理解这个概念呢,举个栗子:
比如你们部门要出去嗨了,准备跟公司申请一笔经费,OK,这个时候一般都会去找人事部对吧,人事部职员一看,帮你核算一下人数,登记一下时间,ok,转达给人事部大佬,大佬接到申请单,扫了一眼,大概没问题了,但是批不了呀他,为啥,因为财政大权不在他手上,他立马转交给了财务部,财务部妹妹接过手,嗯都填的差不多了,就是人数跟经费有点超,他这边不好批,所以转给了财务部大佬,财务部大佬大手一挥,同意,然后层层返回,最后人事跟你说,OK 去嗨吧 记得开发票。
仔细想想,如果不是上帝视角,你觉得你接触的有多少角色? 没错,可能只有第一次的人事妹妹,最后告知你OK的也是她。后面的事你不须理会,哪天后面的流程有变动也不关你事(这就是灵活性),这就是责任链第二大特征。
在Android的源码中,比较经典的责任链场景就是事件分发,有兴趣的筒子可以去了解一下ViewGroup是如何将事件派发到子view的。
好,啰嗦完了,有了这个概念之后咱们继续讲okhttp。
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
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);
return chain.proceed(originalRequest);
}
首先这里定义了一个拦截器集合,里面分别有retryAndFollowUpInterceptor , BridgeInterceptor , CacheInterceptor ,ConnectInterceptor ,CallServerInterceptor, 以及我们在外面自定义的client.interceptors(),client.networkInterceptors(),一个一个来,先看第一个retryAndFollowUpInterceptor
@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) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), 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, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// 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();
}
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;
}
}
有点长,但是我们只看关键点,首先这个拦截器是一个重定向拦截器,他的工作是负责创建一个连接对象,以及处理一些异常看需不需要重新发起请求,首先创建了一个streamAllocation连接对象(注意只是创建,没有连接,请多看他几眼,后面的某一个拦截器你会又看到他的了),传参分别为连接池,连接地址,堆栈对象。接下来创建了一个while循环while (true) {} 其中有一句
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
这里是执行下一个拦截器的意思,从外面一层可以看出接下来的拦截器是BridgeInterceptor,怎样看出是执行下一个呢,我们点开proceed进去,你会发现
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
Connection connection) throws IOException {
<省略部分代码>
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
<省略部分代码>
return response;
}
是吧,index + 1,所以接下来几个拦截器也是通过这样的方式去调用下一个的。
好,回到上面,当执行下个拦截器之后,后面的代码就是等到里面的拦截器执行完了,返回了之后才会继续走的了。
Request followUp = followUpRequest(response);
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
这里是判断是否重定向或者是超时重试,接下来还有一些判断是否超过最大限制
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
以及是否有相同连接
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?");
}
一系列判断,这个拦截器的任务就到这过,简单来讲的一个流程就是
(前)创建连接对象,
开启循环,
执行下一个拦截器,
——(数据返回后)如果有异常,判断是否需要恢复,
检查是否符合要求(符合则返回结果),
是否超过限制(超过抛出异常停止循环),
是否有相同的连接(如果有则复用,没有则新建)。
ok,第一个拦截器的内容过,看第二个BridgeInterceptor
@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");
}
}
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");
}
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 networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
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);
responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
这是一个桥拦截器,放眼望去,是不是看到了很多熟悉的东西?(如果你不熟悉。。。当我没说[反手就是一巴掌.png])
是的,这里在负责请求的拼装,全局的来讲应该称之为转换,因为后面的拦截器返回的数据也会经过这里转换之后才会回到我们刚刚讲的第一个拦截器retryAndFollowUpInterceptor那里去的
Response networkResponse = chain.proceed(requestBuilder.build());
这句代码之上就是一些请求包装,具体的每个点就不细说了,比如cookie什么的,都可以自定义的,否则就添加默认的,这句代码就是执行了下一个拦截器,执行完成后数据返回,接下来
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
public static void receiveHeaders(CookieJar cookieJar, HttpUrl url, Headers headers) {
if (cookieJar == CookieJar.NO_COOKIES) return;
List<Cookie> cookies = Cookie.parseAll(url, headers);
if (cookies.isEmpty()) return;
cookieJar.saveFromResponse(url, cookies);
}
这里解析服务器返回的Hearder(如果cookiejar为空则不做处理)
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");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
这里判断是否支持gzip压缩,可以的话就使用Okio库处理
ok,这个拦截器做的主要是
(前)对Hearder的一些处理,协议的包装(默认还是自定义)
执行下一个拦截器
——(数据返回后)
判断是否支持gzip,
数据处理完返回至上一层拦截器retryAndFollowUpInterceptor
接下来的几个拦截器我们在下一篇讲,文章太长看的脸疼~
Android-OKhttp底层原理浅析(三)
网友评论