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

相关推荐
图书馆钉子户1 小时前
怎么使用ajax实现局部刷新
前端·ajax·okhttp
careathers1 天前
Vue3 + Spring WebMVC 验证码案例中的跨域问题与解决方法
okhttp
linwq82 天前
OkHttp使用和源码分析学习(二)
学习·okhttp
初见_Dream3 天前
Retrofit+OkHttp+ViewModel
xml·okhttp·retrofit
清风细雨_林木木4 天前
wangEditor 编辑器 Vue 2.0 + Nodejs 配置
vue.js·okhttp·编辑器
WeiLai11129 天前
DeepSeekApi对接流式输出异步聊天功能:基于Spring Boot和OkHttp的SSE应用实现
人工智能·spring boot·后端·okhttp
闲暇部落9 天前
Android网络框架——OKHttp
android·java·okhttp
网络安全(华哥)10 天前
CSRF攻击&XSS攻击
okhttp·xss·csrf
不亭11 天前
python自动化测试之统一请求封装及通过文件实现接口关联
okhttp
2501_9032386514 天前
PrimeFaces Poll组件实现周期性Ajax调用
前端·ajax·okhttp·个人开发