从事Android开发多年,做过的项目中http请求框架一直用的OkHttp,从鸿神的okhttputils,到后来的Retrofit,万变不离其宗
应该有很多同学和我一样也都在这使用这些框架,但也只仅仅停留在会用的状态,知道它牛批,用的人最多,但是具体牛批在哪,也说不出个所以然
但是现在都0202了
本着对自己负责的心态和让自己在公司疯狂裁员的处境下能够更加淡然面对(能给我安全感的不只有手机和钱包,还有技术的提高)
于是我默默的打开了https://github.com/square/okhttp
然后就是一连串的懵逼和对自己对OkHttp了解程度的打脸(我以为我用的3.10已经很新了)
😲什么时间可更新到4.3.1版本了?
😲又是什么时间从Java迁移到Kotlin了?
😲api变化大吗?
...
查阅到官方手册
OkHttp 4.x upgrades our implementation language from Java to Kotlin and keeps everything else the same. We’ve chosen Kotlin because it gives us powerful new capabilities while integrating closely with Java.
We spent a lot of time and energy on retaining strict compatibility with OkHttp 3.x. We’re even keeping the package name the same: okhttp3!
概括就是从4.x开始迁移到了Kotlin,并保持与okhttp3.x的严格兼容性,连包名都没变还是okhttp3
看来Kotlin真的是大势所趋啊,幸好在一年多以前已经可以使用kotlin开发了
不废话了,下面介绍OkHttp的基本请求和相应流程,源码就基于目前的最新版4.3.1
1.OkHttp最简单的用法
请求方式分为同步请求和异步请求
val okHttpClient = OkHttpClient.Builder().build()
val request = Request.Builder().url("https://xxxx").build()
//1.同步请求直接返回response
val response = okHttpClient.newCall(request).execute()
//2.异步请求
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
//网络请求失败的回调
}
override fun onResponse(call: Call, response: Response) {
//网络请求成功的回调
}
})
2.流程解析
2.1 创建OkHttpClient
OkHttpClient是通信的客户端实例,用来统一调度发起请求与解析响应
val okHttpClient = OkHttpClient.Builder()
.connectTimeout()
.addInterceptor()
.build()
OkHttpClient使用建造者模式为其设置一些参数,例如超时时间和自定义的拦截器等。一般我们在项目中OkHttpClient都是单例的,因为每个OkHttpClient实例都拥有自己的连接池、线程池和调度器,会对网络请求进行统一管理和连接复用,减少资源浪费和网络延迟
class OkHttpClient {
...
//调度器,内部有线程池
val dispatcher: Dispatcher = builder.dispatcher
//连接池
val connectionPool: ConnectionPool = builder.connectionPool
...
}
2.2 创建Request
Request封装了请求的具体信息,例如请求的url、请求方式、请求头、请求体
class Request internal constructor(
@get:JvmName("url") val url: HttpUrl,
@get:JvmName("method") val method: String,
@get:JvmName("headers") val headers: Headers,
@get:JvmName("body") val body: RequestBody?,
internal val tags: Map<Class<*>, Any>
)
也是通过建造者模式设置这些参数
val request = Request.Builder()
.url()
.post()
.header()
.build()
2.3 创建Call
Call是一个接口,具体的实现类是RealCall,OkHttp的请求也都封装了RealCall中
class OkHttpClient {
...
override fun newCall(request: Request): Call {
return RealCall.newRealCall(this, request, false)
}
...
}
interface Call : Cloneable {
//请求的信息
fun request(): Request
//同步请求,会阻塞线程知道返回结果Response
fun execute(): Response
//异步请求,通过回调得到Response
fun enqueue(responseCallback: Callback)
//取消请求
fun cancel()
//请求是否在执行
fun isExecuted(): Boolean
//请求是否被取消
fun isCanceled(): Boolean
fun timeout(): Timeout
public override fun clone(): okhttp3.Call
interface Factory {
fun newCall(request: Request): okhttp3.Call
}
}
调用OkHttpClient的newCall()方法创建RealCall对象,这时会传入当前OkHttpClient实例this和上一步创建的request
2.4 开始请求
2.4.1 调度器Dispatcher
Dispatcher是OkHttp的一个核心类,负责调度同步和异步请求,取消请求,管理每一个请求的状态,内部维护了一个用来执行异步任务的线程池和三个请求队列,所有的请求Call都要先添加到请求队列
class Dispatcher {
...
//最大任务数
var maxRequests = 64
//同一主机下最大任务数
var maxRequestsPerHost = 5
//准备运行的异步请求
private val readyAsyncCalls = ArrayDeque<RealCall.AsyncCall>()
//正在运行的异步请求
private val runningAsyncCalls = ArrayDeque<RealCall.AsyncCall>()
//正在运行的同步请求
private val runningSyncCalls = ArrayDeque<RealCall>()
//执行异步请求的线程池
private var executorServiceOrNull: ExecutorService? = null
val executorService: ExecutorService
get() {
if (executorServiceOrNull == null) {
executorServiceOrNull = ThreadPoolExecutor(
0, Int.MAX_VALUE, 60, TimeUnit.SECONDS,
SynchronousQueue(), threadFactory("OkHttp Dispatcher", false)
)
}
return executorServiceOrNull!!
}
...
}
2.4.2 同步请求
同步请求会调用RealCall的execute方法,将自己添加进dispatcher的正在执行的任务队列,然后调用getResponseWithInterceptorChain方法得到response,最后又会调用dispatcher的finished方法从队列移除
class Dispatcher {
...
override fun execute(): Response {
synchronized(this) {
//检测是否重复调用
check(!executed) { "Already Executed" }
executed = true
}
transmitter.timeoutEnter()
transmitter.callStart()
try {
//dispatcher的executed方法,将任务添加进正在运行的同步请求队列
client.dispatcher.executed(this)
//调用getResponseWithInterceptorChain方法
return getResponseWithInterceptorChain()
} finally {
//将任务从队列移除
client.dispatcher.finished(this)
}
}
...
}
2.4.3 异步请求
异步请求会调用RealCall的enqueue方法,传入一个Callback用于回调网络请求结果
override fun enqueue(responseCallback: Callback) {
synchronized(this) {
//检测是否重复调用
check(!executed) { "Already Executed" }
executed = true
}
transmitter.callStart()
//dispatcher的enqueue方法
client.dispatcher.enqueue(AsyncCall(responseCallback))
}
RealCall的enqueue方法里面进而又调用okHttpClient的成员dispatcher的enqueue方法,这时候对callback进行的包装,传建一个AsyncCall
class Dispatcher {
...
internal fun enqueue(call: RealCall.AsyncCall) {
...
synchronized(this) {
//添加进准备队列
readyAsyncCalls.add(call)
}
//取出可执行的任务
promoteAndExecute()
}
private fun promoteAndExecute(): Boolean {
...
//可执行任务的集合
val executableCalls = mutableListOf<RealCall.AsyncCall>()
val isRunning: Boolean
synchronized(this) {
val i = readyAsyncCalls.iterator()
while (i.hasNext()) {
val asyncCall = i.next()
//判断是否超过最大任务数
if (runningAsyncCalls.size >= this.maxRequests) break
//判断是否超过同一主机下最大任务数
if (asyncCall.callsPerHost().get() >= this.maxRequestsPerHost) continue
//从等待队列移除
i.remove()
asyncCall.callsPerHost().incrementAndGet()
//添加到可执行任务的集合
executableCalls.add(asyncCall)
//添加到正在运行的队列
runningAsyncCalls.add(asyncCall)
}
isRunning = runningCallsCount() > 0
}
for (i in 0 until executableCalls.size) {
val asyncCall = executableCalls[i]
//执行任务,调用asyncCall的executeOn方法
asyncCall.executeOn(executorService)
}
return isRunning
}
...
}
而AsyncCall又是一个Runnable,会在executeOn中将自己添加到线程池executorService ,在run方法中得到网络请求的结果response
internal inner class AsyncCall(
private val responseCallback: Callback
) : Runnable {
...
//开启任务,执行run方法,此处省略了很多代码
fun executeOn(executorService: ExecutorService) {
var success = false
try {
...
//开启异步任务
executorService.execute(this)
success = true
} catch (e: RejectedExecutionException) {
...
//失败回调
responseCallback.onFailure(this@RealCall, ioException)
} finally {
...
if (!success) {
//如果开启任务失败将任务从队列移除
client.dispatcher.finished(this)
}
}
}
override fun run() {
try {
...
//调用这个方法得到结果response,进行回调
val response = getResponseWithInterceptorChain()
responseCallback.onResponse(this@RealCall, response)
} catch (e: IOException) {
...
//异常也要回调
responseCallback.onFailure(this@RealCall, e)
} catch (t: Throwable) {
...
//异常也要回调
responseCallback.onFailure(this@RealCall, canceledException)
} finally {
...
//不管成功还是失败都要将任务从队列移除
client.dispatcher.finished(this)
}
}
...
}
当调用dispatcher的finished方法时会将当前任务从队列中移除,同时会检查是否还有等待的异步任务
class Dispatcher {
...
internal fun finished(call: RealCall.AsyncCall) {
call.callsPerHost().decrementAndGet()
finished(runningAsyncCalls, call)
}
private fun <T> finished(calls: Deque<T>, call: T) {
...
//继续调用promoteAndExecute方法
val isRunning = promoteAndExecute()
}
...
}
相同点:同步请求和异步请求最终都会调用getResponseWithInterceptorChain方法得到response
class RealCall {
...
fun getResponseWithInterceptorChain(): Response {
// 创建拦截器栈
val interceptors = mutableListOf<Interceptor>()
interceptors += client.interceptors
interceptors += RetryAndFollowUpInterceptor(client)
interceptors += BridgeInterceptor(client.cookieJar)
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)
}
}
}
...
}
到此整个请求就完成了,拿到结果Response,同步请求直接返回,异步请求用Callback进行回调