Last active
February 5, 2020 09:07
-
-
Save Flywith24/f9edaae95e35976105830f5b3f672570 to your computer and use it in GitHub Desktop.
[okhttp-RealCall] RealCall #okhttp #RealCall
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 请求前校验逻辑,仅能执行一次,和过期时间逻辑判断逻辑 | |
* 通知请求start事件,便于metrics 指标数据收集 | |
* 将call加入分发器的同步请求队列中 | |
* 通过拦截器责任链模式进行请求和返回一系列逻辑处理 | |
*/ | |
override fun execute(): Response { | |
// 检查是否已经执行 | |
synchronized(this) { | |
check(!executed) { "Already Executed" } | |
executed = true | |
} | |
// 过期时间逻辑,如果配置了会有WatchDog线程进行Watch然后执行退出逻辑 | |
transmitter.timeoutEnter() | |
// 通知start,最后会通过 EventListener 发出时间,主要目的是收集 metrics events | |
transmitter.callStart() | |
try { | |
// 调用client的dispatcher分发器执行call(将call加入同步call队列) | |
client.dispatcher.executed(this) | |
// 通过拦截器责任链模式进行请求和返回处理等一系类逻辑 | |
return getResponseWithInterceptorChain() | |
} finally { | |
client.dispatcher.finished(this) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getResponseWithInterceptorChain(): Response { | |
// 构建所有的拦截器 | |
val interceptors = mutableListOf<Interceptor>() | |
interceptors += client.interceptors // client配置的拦截器 | |
interceptors += RetryAndFollowUpInterceptor(client) // 重试机制拦截器 | |
interceptors += BridgeInterceptor(client.cookieJar) // 请求和返回桥(http信息配置和解析)拦截器 | |
interceptors += CacheInterceptor(client.cache) // 缓存拦截 | |
interceptors += ConnectInterceptor // 连接拦截器 | |
if (!forWebSocket) { | |
interceptors += client.networkInterceptors | |
} | |
interceptors += CallServerInterceptor(forWebSocket) // 执行拦截器 | |
// 拦截器核心处理类 | |
val chain = RealInterceptorChain(interceptors, transmitter, null, 0, originalRequest, this, | |
client.connectTimeoutMillis, client.readTimeoutMillis, client.writeTimeoutMillis) | |
var calledNoMoreExchanges = false | |
try { | |
// 链式调用 | |
val response = chain.proceed(originalRequest) | |
if (transmitter.isCanceled) { // 处理取消 | |
response.closeQuietly() | |
throw IOException("Canceled") | |
} | |
return response //返回请求结果 | |
} catch (e: IOException) { | |
calledNoMoreExchanges = true | |
throw transmitter.noMoreExchanges(e) as Throwable | |
} finally { | |
if (!calledNoMoreExchanges) { | |
transmitter.noMoreExchanges(null) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment