源码分析基于 3.14.4
拦截器的思想
分层的思想,将一个复杂的网络请求(请求头填充、缓存、重试、建立连接、发起请求)分割成小模块,每个模块负责提供一个能力,符合单一职责原则,也是为了便于维护,不至于修改其中一个节点而影响别的节点,很好地控制影响范围。
发起请求的过程也是执行拦截器的过程
//AsyncCall类中
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());//1
interceptors.add(new RetryAndFollowUpInterceptor(client));//2
interceptors.add(new BridgeInterceptor(client.cookieJar()));//3
interceptors.add(new CacheInterceptor(client.internalCache()));//4
interceptors.add(new ConnectInterceptor(client));//5
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());//6
}
interceptors.add(new CallServerInterceptor(forWebSocket));//7
Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());//8
Response response = chain.proceed(originalRequest);
return response;
}
- 注释1:client.interceptors,自定义应用拦截器,可以添加我们常用的打印日志拦截器,它是最先被执行的;
- 注释2:RetryAndFollowUpInterceptor,重试及重定向拦截器,用于请求失败后的重试;
- 注释3:BridgeInterceptor,桥接拦截器,用于请求前请求头的处理;
- 注释4:CacheInterceptor,缓存拦截器,用于处理缓存;
- 注释5:ConnectInterceptor,连接拦截器,用于处理连接,包括查找可以复用的连接;
- 注释6:client.networkInterceptors,自定义网络请求拦截器,如果使用了缓存,那么该拦截器就不会被触发;
- 注释7:CallServerInterceptor,请求拦截器,用于正在发起请求;
- 注释8:构建拦截器责任链RealInterceptorChain,触发proceed方法,依次执行拦截器;
以上分析有不对的地方,请指出,互相学习,谢谢哦!
网友评论