发表4 分钟读完 (大约610个字)
OkHttp 拦截器的核心源码分析
1. 拦截器接口定义
1 2 3 4 5 6 7 8 9 10
| interface Interceptor { @Throws(IOException::class) fun intercept(chain: Chain): Response
interface Chain { fun request(): Request fun proceed(request: Request): Response } }
|
2. RealInterceptorChain 的核心实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class RealInterceptorChain( private val interceptors: List<Interceptor>, private val index: Int, private val request: Request, ) : Interceptor.Chain {
override fun proceed(request: Request): Response { if (index >= interceptors.size) throw AssertionError()
val next = RealInterceptorChain( interceptors = interceptors, index = index + 1, request = request, )
val interceptor = interceptors[index] val response = interceptor.intercept(next)
return response } }
|
3. OkHttpClient 中的拦截器管理
1 2 3 4 5 6 7 8 9 10 11 12
| class OkHttpClient internal constructor(builder: Builder) { internal val interceptors: List<Interceptor> = builder.interceptors
internal val networkInterceptors: List<Interceptor> = builder.networkInterceptors
class Builder { internal val interceptors: MutableList<Interceptor> = mutableListOf() internal val networkInterceptors: MutableList<Interceptor> = mutableListOf() } }
|
4. 核心执行流程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class RealCall( private val client: OkHttpClient, ) { override fun execute(): Response { val interceptors = mutableListOf<Interceptor>()
interceptors.addAll(client.interceptors)
interceptors.add(RetryAndFollowUpInterceptor(client)) interceptors.add(BridgeInterceptor(client.cookieJar)) interceptors.add(CacheInterceptor(client.cache)) interceptors.add(ConnectInterceptor(client))
interceptors.addAll(client.networkInterceptors)
interceptors.add(CallServerInterceptor())
val chain = RealInterceptorChain( interceptors = interceptors, index = 0, request = originalRequest, )
return chain.proceed(originalRequest) } }
|
5. 内置核心拦截器的职责:
RetryAndFollowUpInterceptor: 处理重试和重定向
BridgeInterceptor: 处理请求头和响应头的转换
CacheInterceptor: 处理请求缓存
ConnectInterceptor: 建立连接
CallServerInterceptor: 与服务器进行实际通信
6. 责任链模式的关键点:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class CustomInterceptor : Interceptor { override fun intercept(chain: Chain): Response { val originalRequest = chain.request()
val modifiedRequest = originalRequest.newBuilder() .addHeader("Custom-Header", "Value") .build()
val response = chain.proceed(modifiedRequest)
return response.newBuilder() .addHeader("Response-Header", "Value") .build() } }
|
这种设计的优点:
- 高度解耦,每个拦截器只负责自己的任务
- 灵活可扩展,可以随时添加或移除拦截器
- 双向处理能力,可以同时处理请求和响应
- 链式调用清晰,调试方便
注意事项:
- 拦截器的添加顺序会影响最终的执行顺序
- 必须调用
chain.proceed() 来继续链条,除非你想中断请求
- 注意处理异常,确保资源正确释放
- 避免在拦截器中执行耗时操作,可能会影响整体性能