美文网首页源码阅读java相关
okhttp3的拦截器机制

okhttp3的拦截器机制

作者: 时间道 | 来源:发表于2018-11-26 22:52 被阅读0次

    okhttp3是目前使用广泛的http调用工具,其基于拦截器的请求处理机制为开发者扩展功能提供了方便,比如通过自定义拦截器实现日志打印、拦截请求、拦截响应等功能。
    okhttp内部总共有两种拦截器:

    1. 应用处理拦截器
    2. 网络处理拦截器NetworkInterceptor

    比如实现日志拦截代码:

    public class LoggingInterceptor implements Interceptor{
        private static final Logger  logger = LoggerFactory.getLogger("rpc");
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long start = System.nanoTime();
            long startTime = System.currentTimeMillis();
            Response response = null;
            try {
                response = chain.proceed(request);
            } catch (Exception e) {
            }
    
            //1、第一部分打印日志 是 rpc.json 的日志
            int code = response == null?504:response.code();
            long time = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
            if (time > CommonConstants.RPC_LOG_MILLISECOND || code > 300){
               
            }
            return response;
        }
    

    拦截器实现原理:

    在RealCall的execute方法执行时,会创建拦截器链,如下代码所示:

    Response getResponseWithInterceptorChain() throws IOException {
            List<Interceptor> interceptors = new ArrayList();
            interceptors.addAll(this.client.interceptors());
            interceptors.add(this.retryAndFollowUpInterceptor);
            interceptors.add(new BridgeInterceptor(this.client.cookieJar()));
            interceptors.add(new CacheInterceptor(this.client.internalCache()));
            interceptors.add(new ConnectInterceptor(this.client));
            if (!this.forWebSocket) {
                interceptors.addAll(this.client.networkInterceptors());
            }
            //主要是通过这个拦截器执行网络请求
            interceptors.add(new CallServerInterceptor(this.forWebSocket));
            Chain chain = new RealInterceptorChain(interceptors, (StreamAllocation)null, (HttpCodec)null, (RealConnection)null, 0, this.originalRequest);
            return chain.proceed(this.originalRequest);
        }
    
    image.png

    各拦截器作用:

    1. RetryAndFollowUpInterceptor 故障恢复,创建StreamAllocation
    2. BridgeInterceptor 网络连接
    3. CacheInterceptor 缓存的读写 DiskLruCache,如何设置开启 cache
    4. ConnectInterceptor 打开一个连接,通过streamAllocation.newStream 创建了httpCodec、realConnection,并且进行了 connect
    5. CallServerInterceptor 发起request,返回response;利用httpCodec提供的I/O操作完成网络通信

    相关文章

      网友评论

        本文标题:okhttp3的拦截器机制

        本文链接:https://www.haomeiwen.com/subject/wzaiqqtx.html