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

相关推荐
4311媒体网4 天前
织梦CMS点击率统计实现方法
okhttp
帅次5 天前
链路到端上:HTTPS 之后安全题还在考什么
android·okhttp·glide·zygote·retrofit
djk88886 天前
layui zTree 控件 AJAX绑定 点击tree事件 获取tree值
ajax·okhttp·layui
明天就是Friday8 天前
Android实战项目④ OkHttp WebSocket开发即时通讯App 完整源码详解
android·websocket·okhttp
xiangxiongfly9158 天前
Android 使用WebSocket通信
android·websocket·网络协议·okhttp
研☆香9 天前
聊聊什么是AJAX
前端·ajax·okhttp
sunwenjian88611 天前
跨域问题解释及前后端解决方案(SpringBoot)
spring boot·后端·okhttp
XiaoLeisj13 天前
Android 短视频播放详情页实战:从播放器模块拆分、Media3 与 FlowHelper 接入,到 ViewPager 高度适配和详情数据联动
android·okhttp·音视频·架构设计·flowhelper
阿正的梦工坊14 天前
拦截网络请求:一种更优雅的数据获取方式
网络·okhttp
鬼蛟19 天前
ICAN_PARENT
okhttp