http://blog.youkuaiyun.com/z69183787/article/details/43451413
http://www.chinabaike.com/z/shenghuo/kp/2017/0131/6118030.html?1485866994
http://blog.youkuaiyun.com/oyangyujun/article/details/50039403
okhttp拦截器实现原理:拦截器执行顺序是从第0个开始。
private 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 (!retryAndFollowUpInterceptor.isForWebSocket()) { interceptors.addAll(client.networkInterceptors()); } interceptors.add(new CallServerInterceptor(//最后一个拦截器,实现网络请求 retryAndFollowUpInterceptor.isForWebSocket())); Interceptor.Chain chain = new RealInterceptorChain( interceptors, null, null, null, 0, originalRequest); return chain.proceed(originalRequest); }
CallServerInterceptor的实现里没有chain.proceed(request),就不会递归调用了。
RealInterceptorChainh执行的核心:
举例:
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request); //关键一步,递归调用,形成一个链条。
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}