android开发okhttp-4.9.1源码大致流程解读

okhttp-4.9.1源码大致流程解读

val okHttpClient = OkHttpClient()
val request: Request = Request.Builder().url("https://xxx.com/index").build()
okHttpClient.newCall(request).enqueue(object:Callback{...})

//由dispatcher添加到readyAsyncCalls队列ArrayDeque
OkHttpClient.dispatcher.enqueue(AsyncCall(responseCallback))
//接着检查runningAsyncCalls是否大于maxRequests默认64,不大于则从runningAsyncCalls移除,
//并添加到runningAsyncCalls,接着executeOn开始执行
Dispatcher.promoteAndExecute()
RealCall.executeOn
	executorService.execute(this)//this指向RealCall$AsyncCall内部类,然后就是执行AsyncCall的run方法了

//看名字意思,通过拦截器链获取结果,默认是下面这些拦截器
getResponseWithInterceptorChain(){
    val interceptors = mutableListOf<Interceptor>()
    interceptors += client.interceptors	//用户定义添加的拦截器	
    interceptors += RetryAndFollowUpInterceptor(client)	//失败重试和追踪重定向拦截器
    interceptors += BridgeInterceptor(client.cookieJar) //桥接拦截器,就是构建请求对象、处理网络调用、构建响应对象
    interceptors += CacheInterceptor(client.cache)	//缓存拦截器,从缓存查询请求结果、缓存网络响应的结果
    interceptors += ConnectInterceptor //打开Socket并握手,RealConnection类,realChain.call.initExchange(chain)
    if (!forWebSocket) {
      interceptors += client.networkInterceptors	//用户定义的网络拦截器
    }
    interceptors += CallServerInterceptor(forWebSocket)	//调用服务器拦截器,最后一个拦截器,发送网络调用返回响应结果
    val chain = RealInterceptorChain(call = this,interceptors = interceptors,...)
	val response = chain.proceed(originalRequest) 	//开始按照添加的拦截器顺序逐个执行拦截器
}
//最后返回response结果给用户的回调函数,整个流程结束。。。
responseCallback.onResponse(this@RealCall, response)

可见,okhttp的核心实现是内置的五个拦截器的逻辑实现,分别是:

RetryAndFollowUpInterceptor BridgeInterceptor CacheInterceptor ConnectInterceptor CallServerInterceptor

这些拦截器源码再另行研究研究吧。。。

posted @   yongfengnice  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2019-07-30 dagger2的使用总结
点击右上角即可分享
微信分享提示