okhttp系列-拦截器的执行顺序

1.将拦截器添加到ArrayList

java 复制代码
final class RealCall implements Call {
    Response getResponseWithInterceptorChain() throws IOException {
        //将Interceptor添加到ArrayList
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.addAll(client.interceptors());
        interceptors.add(new RetryAndFollowUpInterceptor(client));
        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));

        //第一次的index为0
        Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 
        0, originalRequest, this, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

        //执行请求后,得到结果
        Response response = chain.proceed(originalRequest);
        return response;
    }
}

2.拦截器的执行-责任链模式

java 复制代码
public final class RealInterceptorChain implements Interceptor.Chain {
    private final int index; //当前运行的Interceptor在ArrayList的索引

    public Response proceed(Request request, Transmitter transmitter, 
             @Nullable Exchange exchange)
      throws IOException {
        //每次index都基于上次的index +1,这样每次取得的就是下一个拦截器
        RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, 
         exchange, index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
        Interceptor interceptor = interceptors.get(index);
        //执行拦截器的方法的时候,携带了RealInterceptorChain作为参数,这样可以
        //调用这个chain的proceed
        Response response = interceptor.intercept(next);
        return response;
    }
}

3.总结

按照责任链模式执行拦截器

拦截器的执行顺序:

RetryAndFollowUpInterceptor:执行下一个拦截器,针对结果或者处理过程中的异常来进行重试或者重定向;

BridgeInterceptor:补充headers;执行下一个拦截器;处理返回的response;

CacheInterceptor:结果缓存,如果能用就返回缓存;如果不能用就执行下一个拦截器;

ConnectInterceptor:

CallServerInterceptor

相关推荐
小羊没烦恼!9 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
脉动数据行情1 天前
Java OkHttp 对接国际期货批量行情 SpringBoot 定时落库实践
java·spring boot·okhttp
牧瀬クリスだ7 天前
Ajax入门:从原生XHR到axios实战
java·spring boot·ajax·okhttp
墨天梦10 天前
B15_HTTP解析与OkHttp拦截器
网络协议·http·okhttp
没差c1 个月前
RetrofitClient写接口、导包、配置、路径
java·spring boot·okhttp
事圆则缓1 个月前
OkHttp + Retrofit 协作原理
okhttp·retrofit
降临-max1 个月前
接口自动化(TestNG+OKHttp)
软件测试·okhttp·自动化·testng
吴声子夜歌1 个月前
Java扩展——OkHttp
java·开发语言·okhttp
额鹅恶饿呃1 个月前
Asynchronous JavaScript And XML(异步的JS和XML )
okhttp
泡海椒1 个月前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp