OkHttp3 源码详解之拦截器(四),计算机应届毕业生面试题
调用 getResponseWithInterceptorChain 获取服务器返回通知任务分发器(client.dispatcher)该任务已结束 getResponseWithInterceptorChain 构建了一个拦截器链,通过依次执行该拦截器链中的每一个拦截器最终得到服务器返回。
3. 构建拦截器链首先来看下 getResponseWithInterceptorChain 的实现:
源码路径:okhttp3/RealCall.java
// 开始执行整个请求 Response getResponseWithInterceptorChain() throws IOException {// Build a full stack of interceptors.// 拦截器栈 List<Interceptor> interceptors = new ArrayList<>();// 前文说过的 普通拦截器 interceptors.addAll(client.interceptors());// 重试拦截器,网络错误、请求失败等 interceptors.add(retryAndFollowUpInterceptor);// 桥接拦截器,主要是重构请求头即 headerinterceptors.add(new BridgeInterceptor(client.cookieJar()));// 缓存拦截器 interceptors.add(newCacheInterceptor(client.internalCache()));// 连接拦截器,连接服务器,https 包装 interceptors.add(new ConnectInterceptor(client));// 网络拦截器,websockt 不支持,同样是自定义 if (!forWebSocket) {interceptors.addAll(client.networkInterceptors());}// 服务拦截器,主要是发送(write、input)、读取(read、output)数据 interceptors.add(new CallServerInterceptor(forWebSocket));
// 开启调用链 Interceptor.Chain chain = new RealInterceptorChain(interceptors, , originalRequest);return chain.proceed(originalRequest);}
其逻辑大致分为两部分:
创建一系列拦截器,并将其放入一个拦截器数组中。这部分拦截器即包括用户自定义的拦截器也包括框架内部拦截器创建一个拦截器链 RealInterceptorChain,并执行拦截器链的 proceed 方法接下来看下 RealInterceptorChain 的实现逻辑:
public final class RealInterceptorChain implements Interceptor.Chain {private final List<Interceptor> interceptors;private final StreamAllocation streamAllocation;private final HttpCodec httpCodec;private final RealConnection connection;private final int index;private final Request request;private int calls;
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,HttpCodec httpCodec, RealConnection connection, int index, Request request) {this.interceptors = interceptors;this.connection = connection;this.streamAllocation = streamAllocation;this.httpCodec = httpCodec;this.index = index;this.request = request;}
@Override public Connection connection() {return connection;}
public StreamAllocation streamAllocation() {return streamAllocation;}
public HttpCodec httpStream() {return httpCodec;}
@Override public Request request() {return request;}
@Override public Response proceed(Request request) throws IOException {return proceed(request, streamAllocation, httpCodec, connection);}
public Response proceed(Request reque
st, StreamAllocation streamAllocation, HttpCodec httpCodec,RealConnection connection) throws IOException {
......// Call the next interceptor in the chain.RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + , request);Interceptor interceptor = interceptors.get(index);Response response = interceptor.intercept(next);
......
return response;}}
在 proceed 方法中的核心代码可以看到,proceed 实际上也做了两件事:
创建下一个拦截链。传入 index + 1 使得下一个拦截器链只能从下一个拦截器开始访问执行索引为 index 的 intercept 方法,并将下一个拦截器链传入该方法。原文链接:https://www.bbsmax.com/A/MAzAEmQMz9/**阿里 P7 移动互联网架构师进阶视频(每日更新中)免费学习请点击:[https://space.bilibili.com/474380680](
)**
评论