分析的okhttp版本为
implementation("com.squareup.okhttp3:okhttp:4.9.1")
RealCall.kt文件中 有一个函数 fun getResponseWithInterceptorChain():Response 这个函数中是拦截器相关逻辑的开始。
@Throws(IOException::class)
internal fun getResponseWithInterceptorChain(): Response {
// 构建一个拦截器可变列表,添加全部拦截器到这个列表
val interceptors = mutableListOf<Interceptor>()
interceptors += client.interceptors //用户自己定义的拦截器
//以下全部是okhttp内置拦截器
interceptors += RetryAndFollowUpInterceptor(client)
interceptors += BridgeInterceptor(client.cookieJar)
interceptors += CacheInterceptor(client.cache)
interceptors += ConnectInterceptor
if (!forWebSocket) {
interceptors += client.networkInterceptors
}
//真正发起请求的拦截器
interceptors += CallServerInterceptor(forWebSocket)
//构建拦截器请求chain,注意此处为起始chain
val chain = RealInterceptorChain(
call = this,
interceptors = interceptors, //全部拦截器列表
index = 0,//需要处理的拦截器列表的index
exchange = null,
request = originalRequest,//起初构建的 Request 对象
connectTimeoutMillis = client.connectTimeoutMillis,
readTimeoutMillis = client.readTimeoutMillis,
writeTimeoutMillis = client.writeTimeoutMillis
)
var calledNoMoreExchanges = false
try {
//执行拦截器
val response = chain.proceed(originalRequest)
if (isCanceled()) {
response.closeQuietly()
throw IOException("Canceled")
}
return response
} catch (e: IOException) {
calledNoMoreExchanges = true
throw noMoreExchanges(e) as Throwable
} finally {
if (!calledNoMoreExchanges) {
noMoreExchanges(null)
}
}
}
通过RealInterceptorChain的构造方法也大致可以推断出它内部所包含的对象数据和方法
//简写,伪代码
class RealInterceptorChain(
allInterceptor:mutableListOf<Interceptor>,//全部的拦截器
index:Int//当前需要处理拦截器列表哪一个拦截器的index
originalRequest:Request//原始的请求提对象
){
//执行
fun proceed(r:Request){}
}
看一下proceed()做了什么
@Throws(IOException::class)
override fun proceed(request: Request): Response {
//此处省略一部分代码...
//构建下一个chain (RealInterceptorChain)
val next = copy(index = index + 1, request = request)
//取出当下拦截器,注意下次这个index 会被+1
val interceptor = interceptors[index]
//通过拦截器调用intercept()并把对应的chain传入拦截器
val response = interceptor.intercept(next) ?: throw NullPointerException(
"interceptor $interceptor returned null")
//此处省去一部分代码...
return response //返回响应体对象
}
现在来看一张图
这张图诠释了拦截器的调用顺序与内存对象关系,简单梳理一下:
真正的调用是第一个RealInterceptorChain对象发起的,通过它的proceed()方法,构建出一个Chain对象,并找到一个拦截器,把这个chain对象传递给这个拦截器,通过拦截器中的chain再次调用proceed()重复上面的动作。
直到CallServerInterceptor拦截器为止开始返回Response对象,之后就是拦截器中的chain.proceed(req)后面的调用被执行(递归)。
通过了解了拦截器的实现机制,我们在定义拦截器时,就可以毫不费力了。
比如如下定义的拦截器:
/**
* 缓存策略拦截器
*/
class CacheInterceptor(var day: Int = 7) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()//获取RealInterceptorChain中的request对象
if (!NetworkUtil.isNetworkAvailable(appContext)) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build()
}
val response = chain.proceed(request)//执行RealInterceptorChain中的proceed()继而达到调用下一个拦截器的目的
//以下都是在CallServerInterceptor拦截器返回后被调用
if (!NetworkUtil.isNetworkAvailable(appContext)) {
val maxAge = 60 * 60
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=$maxAge")
.build()
} else {
val maxStale = 60 * 60 * 24 * day // tolerate 4-weeks stale
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
.build()
}
return response
}
}
我们看到自定义拦截器最关心的两个方法是
var request = chain.request() //就是获取chain中保存的request对象
val response = chain.proceed(request) //执行下一个拦截器,直到CallServerInterceptor返回
我们在简单看一下CallServerInterceptor
class CallServerInterceptor{
override fun intercept(chain: Interceptor.Chain): Response {
val realChain = chain as RealInterceptorChain
val request = realChain.request
val requestBody = request.body
requestBody.writeTo(bufferedRequestBody) //真正使用request对象
var response = responseBuilder//真正创建 response 对象
.request(request)
.handshake(exchange.connection.handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build()
return response
}
}
到此 拦截器分析完毕!