OkHttp3 超时设置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OkHttp3 超时设置相关的知识,希望对你有一定的参考价值。

参考技术A 目录

1,AsyncTimeout

2-1,耗时段介绍「从上往下」

2-2,4个超时设置「OkHttpClient.Builder」

2-3,耗时操作之间的关联

0,参考
okhttp Timeout 超时设置与用法解释: https://www.jianshu.com/p/7547a5e8524a

1,AsyncTimeout

AsyncTimeout.enter 案例
1,首次创建 Watchdog + AsyncTimeout作为static量,避免重复创建
2,单线程,设置超时,通过pine/pip机制,若超时通过写入流方式唤醒

2-1,耗时段介绍「从上往下」
耗时操作 调用位置
DNS解析 「ConnectInterceptor」streamAllocation.newStream
「RouteSelector」address.dns().lookup()
连接时间 「ConnectInterceptor」streamAllocation.newStream
「Platform」socket.connect()
写入request 「CallServerInterceptor」httpCodec.writeRequestHeaders
服务器响应 「ConnectInterceptor」streamAllocation.newStream
「RealConnection」socket.connect()
读取response 「CallServerInterceptor」httpCodec.readResponseHeaders

2-2,4个超时设置「OkHttpClient.Builder」
api 简介 生效机制
callTimeout() 整个流程耗费的超时时间 RealCall.execute方法,设置进入
AsyncTimeout + WatchDog实现
connectTimeout() 三次握手 + SSL建立耗时 socket.connect(address, connectTimeout)
readTimeout() source读取耗时 source.timeout(readTimeout)
AsyncTimeout + WatchDog实现
rawSocket读取耗时 rawSocket.setSoTimeout(readTimeout)
writeTimeout() sink写入耗时 sink.timeout(writeTimeout)
AsyncTimeout + WatchDog实现
重点说一下,callTimeout这个参数,网络上很少人使用。这个就是整个网络流程的超时设置。

2-3,耗时操作之间的关联
route.requiresTunnel() callTimeout = dns + connection + readTimeout + readTimeout + writeTimeout + 其它
无 callTimeout = dns + connectTime + readTimeout + 其它
1,基本耗时:dns + 三次握手耗时 + 服务器响应耗时
2,若有渠道,则增加 source.timeout().(readTimeout) + sink.timeout.(writeTimeout)

以上是关于OkHttp3 超时设置的主要内容,如果未能解决你的问题,请参考以下文章

okhttp3怎么设置代理

OkHttp3 readError问题解决

Android OkHttp3 上传多张图片

okhttp3 post请求基本使用以及超时重连

Picasso:设置旧版本的 OkHttp3

RestTemplate + OkHttp3 - gzip'ed响应的透明处理?