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>()

// 1. 添加用户自定义的应用拦截器
interceptors.addAll(client.interceptors)

// 2. 添加OkHttp内置的核心拦截器
interceptors.add(RetryAndFollowUpInterceptor(client))
interceptors.add(BridgeInterceptor(client.cookieJar))
interceptors.add(CacheInterceptor(client.cache))
interceptors.add(ConnectInterceptor(client))

// 3. 添加用户自定义的网络拦截器
interceptors.addAll(client.networkInterceptors)

// 4. 添加服务器通信拦截器
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 {
// 1. 获取原始请求
val originalRequest = chain.request()

// 2. 处理请求(可选)
val modifiedRequest = originalRequest.newBuilder()
.addHeader("Custom-Header", "Value")
.build()

// 3. 转发给下一个拦截器
val response = chain.proceed(modifiedRequest)

// 4. 处理响应(可选)
return response.newBuilder()
.addHeader("Response-Header", "Value")
.build()
}
}

这种设计的优点:

  1. 高度解耦,每个拦截器只负责自己的任务
  2. 灵活可扩展,可以随时添加或移除拦截器
  3. 双向处理能力,可以同时处理请求和响应
  4. 链式调用清晰,调试方便

注意事项:

  1. 拦截器的添加顺序会影响最终的执行顺序
  2. 必须调用 chain.proceed() 来继续链条,除非你想中断请求
  3. 注意处理异常,确保资源正确释放
  4. 避免在拦截器中执行耗时操作,可能会影响整体性能
作者

Dench

发布于

2025-04-12

更新于

2025-04-12

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×