Each interceptor chain has relative merits.
每个拦截器各有自己的优点
Application interceptors:应用拦截器
Don’t need to worry about intermediate responses like redirects and retries.
Are always invoked once, even if the HTTP response is served from the cache.
Observe the application’s original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
Permitted to short-circuit and not call Chain.proceed().
Permitted to retry and make multiple calls to Chain.proceed().
*不必要担心响应和重定向之间的中间响应。
*通常只调用一次,即使HTTP响应是通过缓存提供的。
*遵从应用层的最初目的。与OkHttp的注入头部无关,如If-None-Match。
*允许短路而且不调用Chain.proceed()。
*允许重试和多次调用Chain.proceed()。
Network Interceptors:网络拦截器
Able to operate on intermediate responses like redirects and retries.
Not invoked for cached responses that short-circuit the network.
Observe the data just as it will be transmitted over the network.
Access to the Connection that carries the request.
*允许像重定向和重试一样操作中间响应。
*网络发生短路时不调用缓存响应。
*在数据被传递到网络时观察数据。
*有权获得装载请求的连接。
getResponseWithInterceptorChain方法:
final class RealCall implements Call {
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.interceptors
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());//应用拦截器
//重定向、重试
interceptors.add(retryAndFollowUpInterceptor);
//用户应用层和网络从桥梁。主要包含:
//1. 将用户的request,转变为网络层的request,比如添加各种请求头,UA ,Cookie , Content-Type等。
//2. 将网络层的response转变为用户层的response,比如解压缩,除去各种请求头等。
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));
//第一个chain
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
//通过链式请求的得到response
return chain.proceed(originalRequest);
}
}
proceed方法:
public final class RealInterceptorChain implements Interceptor.Chain {
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
//....
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);//下一个chain
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
//...
return response;
}
}