OkHttp源码解析(二)- Interceptors 拦截器链工作流程

2024-02-18 17:32

本文主要是介绍OkHttp源码解析(二)- Interceptors 拦截器链工作流程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

OkHttp的配置、使用步骤这里就不展开描述了,网络上有很多优秀的文章,这里主要是对学习源码中理解到的知识进行概括总结。

该文章根据OkHttp-3.11.0版本进行分析,并且强烈建议自己跟着源码配合文章的思路一起阅读

拦截器链是如何在OkHttp请求过程中被调用的请看我的另一篇文章:
OkHttp源码解析(一)- Dispatcher

  • 拦截器链

    意义:采用责任链模式,链中的每一个拦截器只做自己所负责的事情,将对Request的处理结果交给下一个拦截器,从最后一个拦截器开始,将返回结果依次返回给上一个拦截器,最终返回完整的Response结果。

    拦截器类型
    1. 用户自定义拦截器
    2. RetryAndFollowUpInterceptor:处理重试、重定向机制的拦截器。
    3. BridgeInterceptor:处理流大小、压缩、编码的拦截器。
    4. CacheInterceptor:处理缓存的拦截器。
    5. ConnectInterceptor:处理连接的拦截器。
    6. NetworkInterceptors:用户自定义的处理网络请求与响应的拦截器。
    7. CallServerInterceptor:处理与服务器交互细节的拦截器。

    拦截器定义的源码如下:

// Build a full stack of interceptors.
List<Interceptorinterceptors = 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));

我们用流程图的形式来描述拦截器链的工作过程:
Interceptors工作流程
从我的另一篇文章可以知道,拦截器链开始工作是通过 RealCall 当中的 getResponseWithInterceptorChain() 方法,我们看一下这个方法的源码:

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 (!forWebSocket) {interceptors.addAll(client.networkInterceptors());}interceptors.add(new CallServerInterceptor(forWebSocket));Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,originalRequest, this, eventListener, client.connectTimeoutMillis(),client.readTimeoutMillis(), client.writeTimeoutMillis());return chain.proceed(originalRequest);
}

可以看到各个不同的拦截器是按顺序添加进ArrayList中,在最后几行代码中构建了一个 RealInterceptorChain 对象,重点关注构造方法传递的第一个和第五个参数,第一个参数是拦截器的List集合, 第五个参数这里传的是0 ,这里加粗是需要注意这里传的是0。RealInterceptorChain 对象构建完之后立刻调用的自己的 proceed() 方法,我们跟踪进去看:

//构造方法
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {this.interceptors = interceptors;this.connection = connection;this.streamAllocation = streamAllocation;this.httpCodec = httpCodec;this.index = index;this.request = request;this.call = call;this.eventListener = eventListener;this.connectTimeout = connectTimeout;this.readTimeout = readTimeout;this.writeTimeout = writeTimeout;
}//proceed方法
@Override public Response proceed(Request request) throws IOException {return proceed(request, streamAllocation, httpCodec, connection);}public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,RealConnection connection) throws IOException {if (index >= interceptors.size()) throw new AssertionError();calls++;// If we already have a stream, confirm that the incoming request will use it.if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)+ " must retain the same host and port");}// If we already have a stream, confirm that this is the only call to chain.proceed().if (this.httpCodec != null && calls > 1) {throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)+ " must call proceed() exactly once");}// Call the next interceptor in the chain.RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,writeTimeout);Interceptor interceptor = interceptors.get(index);Response response = interceptor.intercept(next);// Confirm that the next interceptor made its required call to chain.proceed().if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {throw new IllegalStateException("network interceptor " + interceptor+ " must call proceed() exactly once");}// Confirm that the intercepted response isn't null.if (response == null) {throw new NullPointerException("interceptor " + interceptor + " returned null");}if (response.body() == null) {throw new IllegalStateException("interceptor " + interceptor + " returned a response with no body");}return response;
}

在构造方法当中可以看到只做了赋值操作,把index赋给了全局变量index,然后在proceed中调用了自己的4个参数的重载方法。在这个重载方法中我们忽略掉那些判断,重点关注其中的几行代码:

// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);

第一行就 new 了自己,又构建了一个对象,但是这次跟之前不同的是第5个参数 index+1,这里让下标增加了1,紧接着从拦截器的List集合中获取到当前下标的拦截器,这个时候我们应该能知道会发生什么,在 RealCall 中第一次构建 RealInterceptorChain 对象时,index为0,等到新的 RealInterceptorChain 对象执行它的 proceed() 方法时,index会+1,以此类推,直到index的值超过拦截器List集合的大小为止。

但是看到这里我们也只是看到取出了拦截器,下一次 RealInterceptorChain 调用 proceed() 是什么时候呢?我们再看下一行代码,将当前下标的拦截器取出之后,立即执行的它(拦截器)的 intercept() 方法,并且将 第五个参数为index+1RealInterceptorChain 对象作为参数传递进去,联系到文章之前添加拦截器的顺序,我们假设没有添加自定义的拦截器,那么现在第一个拦截器就是 RetryAndFollowUpInterceptor ,我们跟踪到这个拦截器的 intercept() 方法中去,记住,这个方法中的参数index是进行了+1操作的:

//这里的源码会忽略跟本篇文章分析拦截器工作流程无关的一部分代码
@Override public Response intercept(Chain chain) throws IOException {Request request = chain.request();RealInterceptorChain realChain = (RealInterceptorChain) chain;Call call = realChain.call();EventListener eventListener = realChain.eventListener();//忽略部分代码while (true) {if (canceled) {streamAllocation.release();throw new IOException("Canceled");}Response response;boolean releaseConnection = true;try {response = realChain.proceed(request, streamAllocation, null, null);releaseConnection = false;} catch (RouteException e) {// The attempt to connect via a route failed. The request will not have been sent.if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {throw e.getFirstConnectException();}releaseConnection = false;continue;} catch (IOException e) {// An attempt to communicate with a server failed. The request may have been sent.boolean requestSendStarted = !(e instanceof ConnectionShutdownException);if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;releaseConnection = false;continue;} finally {// We're throwing an unchecked exception. Release any resources.if (releaseConnection) {streamAllocation.streamFailed(null);streamAllocation.release();}}//忽略部分代码}
}

我们可以看到,首先将参数 chain 强转为 RealInterceptorChain ,然后在 try代码块 中又调用了 **proceed()**方法,这时我们再回到 RealInterceptorChain 的 **proceed()**方法中,此时index+1,取出的拦截器就是集合中第二次添加的 BridgeInterceptor 了,如此反复该项操作。

最后能够发现,在每一个拦截器的 proceed() 方法中都会对之前拦截器处理过的 request 再做自己的处理,处理之后返回 response 给上一个拦截器,这也印证了文章开头的介绍拦截器链意义的那句话以及流程图中 requestresponse 的传递顺序。

至于OkHttp中已经定义好的拦截器做了什么工作、我们自定义拦截器能够做什么工作,我找到了一篇讲解的比较好的文章:okhttp3源码分析之拦截器。

这篇关于OkHttp源码解析(二)- Interceptors 拦截器链工作流程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/721912

相关文章

Java中的runnable 和 callable 区别解析

《Java中的runnable和callable区别解析》Runnable接口用于定义不需要返回结果的任务,而Callable接口可以返回结果并抛出异常,通常与Future结合使用,Runnab... 目录1. Runnable接口1.1 Runnable的定义1.2 Runnable的特点1.3 使用Ru

Spring 中 BeanFactoryPostProcessor 的作用和示例源码分析

《Spring中BeanFactoryPostProcessor的作用和示例源码分析》Spring的BeanFactoryPostProcessor是容器初始化的扩展接口,允许在Bean实例化前... 目录一、概览1. 核心定位2. 核心功能详解3. 关键特性二、Spring 内置的 BeanFactory

使用EasyExcel实现简单的Excel表格解析操作

《使用EasyExcel实现简单的Excel表格解析操作》:本文主要介绍如何使用EasyExcel完成简单的表格解析操作,同时实现了大量数据情况下数据的分次批量入库,并记录每条数据入库的状态,感兴... 目录前言固定模板及表数据格式的解析实现Excel模板内容对应的实体类实现AnalysisEventLis

Spring Boot拦截器Interceptor与过滤器Filter详细教程(示例详解)

《SpringBoot拦截器Interceptor与过滤器Filter详细教程(示例详解)》本文详细介绍了SpringBoot中的拦截器(Interceptor)和过滤器(Filter),包括它们的... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)详细教程1. 概述1

kotlin中的模块化结构组件及工作原理

《kotlin中的模块化结构组件及工作原理》本文介绍了Kotlin中模块化结构组件,包括ViewModel、LiveData、Room和Navigation的工作原理和基础使用,本文通过实例代码给大家... 目录ViewModel 工作原理LiveData 工作原理Room 工作原理Navigation 工

Java的volatile和sychronized底层实现原理解析

《Java的volatile和sychronized底层实现原理解析》文章详细介绍了Java中的synchronized和volatile关键字的底层实现原理,包括字节码层面、JVM层面的实现细节,以... 目录1. 概览2. Synchronized2.1 字节码层面2.2 JVM层面2.2.1 ente

在VSCode中本地运行DeepSeek的流程步骤

《在VSCode中本地运行DeepSeek的流程步骤》本文详细介绍了如何在本地VSCode中安装和配置Ollama和CodeGPT,以使用DeepSeek进行AI编码辅助,无需依赖云服务,需要的朋友可... 目录步骤 1:在 VSCode 中安装 Ollama 和 CodeGPT安装Ollama下载Olla

Redis 内存淘汰策略深度解析(最新推荐)

《Redis内存淘汰策略深度解析(最新推荐)》本文详细探讨了Redis的内存淘汰策略、实现原理、适用场景及最佳实践,介绍了八种内存淘汰策略,包括noeviction、LRU、LFU、TTL、Rand... 目录一、 内存淘汰策略概述二、内存淘汰策略详解2.1 ​noeviction(不淘汰)​2.2 ​LR

IDEA与JDK、Maven安装配置完整步骤解析

《IDEA与JDK、Maven安装配置完整步骤解析》:本文主要介绍如何安装和配置IDE(IntelliJIDEA),包括IDE的安装步骤、JDK的下载与配置、Maven的安装与配置,以及如何在I... 目录1. IDE安装步骤2.配置操作步骤3. JDK配置下载JDK配置JDK环境变量4. Maven配置下

linux环境openssl、openssh升级流程

《linux环境openssl、openssh升级流程》该文章详细介绍了在Ubuntu22.04系统上升级OpenSSL和OpenSSH的方法,首先,升级OpenSSL的步骤包括下载最新版本、安装编译... 目录一.升级openssl1.官网下载最新版openssl2.安装编译环境3.下载后解压安装4.备份