OkHttp框架源码深度剖析【Android热门框架分析第一弹】

OkHttp介绍

OkHttp是当下Android使用最频繁的网络请求框架,由Square公司开源。Google在Android4.4以后开始将源码中的HttpURLConnection底层实现替换为OKHttp,同时现在流行的Retrofit框架底层同样是使用OKHttp的。

源码传送门

优点:

  • 支持Http1、Http2、Quic以及WebSocket
  • 连接池复用底层TCP(Socket),减少请求延时
  • 无缝的支持GZIP减少数据流量
  • 缓存响应数据减少重复的网络请求
  • 请求失败自动重试主机的其他ip,自动重定向

OkHttp使用流程图

在使用OkHttp发起一次请求时,对于使用者最少存在 OkHttpClientRequestCall 三个角色。其中 OkHttpClient 和 Request 的创建可以使用它为我们提供的 Builder (建造者模式)。而 Call 则是把 Request 交 给 OkHttpClient 之后返回的一个已准备好执行的请求。

建造者模式:将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。实例化 OKHttpClient和Request的时候,因为有太多的属性需要设置,而且开发者的需求组合千变万化,使用建造 者模式可以让用户不需要关心这个类的内部细节,配置好后,建造者会帮助我们按部就班的初始化表示对象

大家要记住这个流程图,对我们的请求逻辑有一个大概的印象。

OkHttp基本使用

 
  1. // 1.创建client

  2. OkHttpClient client = new OkHttpClient().newBuilder()

  3. .cookieJar(CookieJar.NO_COOKIES)

  4. .callTimeout(10000, TimeUnit.MILLISECONDS)

  5. .build();

  6. // 2.创建request

  7. Request request = new Request.Builder()

  8. .url("http://10.34.12.156:68080/admin-api")

  9. .addHeader("Content-Type", "application/json")

  10. .get();

  11. .build();

  12. // 3.构建call对象

  13. Call call = client.newCall(request);

  14. // 4.1调用call对象的同步请求方法

  15. Response response = call.execute();// response对象中保存的有返回的响应参数

  16. // 4.2调用call对象的异步请求方法

  17. call.enqueue(new Callback() {

  18. @Override

  19. public void onFailure(@NonNull Call call, @NonNull IOException e) {

  20. Log.d(TAG, "onFailure: ");// 失败回调

  21. }

  22. @Override

  23. public void onResponse(@NonNull Call call, @NonNull Response response) {

  24. Log.d(TAG, "onResponse: ");// 成功回调

  25. }

  26. });

第一步,通过建造者模式创建我们的OkHttpClient对象。

第二步,创建我们的Request请求,把Url、请求头什么的加上,这里也使用了建造者模式。

第三步,创建我们的Call对象,然后就可以开始我们的网络请求了。这块也是我们需要详细分析的部分。

这里是通过client对象的newCakk方法拿到了我们的Call对象,那么newCall方法是什么呢?

查看源码发现,newCall方法返回一个Call对象,是通过RealCall方法返回的。此时,我们需要回过头看看,Call到底是什么?下面的Call的部分源码。

 
  1. interface Call : Cloneable {

  2. /** Returns the original request that initiated this call. */

  3. fun request(): Request

  4. /**

  5. * Invokes the request immediately, and blocks until the response can be processed or is in error.

  6. *

  7. * To avoid leaking resources callers should close the [Response] which in turn will close the

  8. * underlying [ResponseBody].

  9. *

  10. * ```

  11. * // ensure the response (and underlying response body) is closed

  12. * try (Response response = client.newCall(request).execute()) {

  13. * ...

  14. * }

  15. * ```

  16. *

  17. * The caller may read the response body with the response's [Response.body] method. To avoid

  18. * leaking resources callers must [close the response body][ResponseBody] or the response.

  19. *

  20. * Note that transport-layer success (receiving a HTTP response code, headers and body) does not

  21. * necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP

  22. * response code like 404 or 500.

  23. *

  24. * @throws IOException if the request could not be executed due to cancellation, a connectivity

  25. * problem or timeout. Because networks can fail during an exchange, it is possible that the

  26. * remote server accepted the request before the failure.

  27. * @throws IllegalStateException when the call has already been executed.

  28. */

  29. @Throws(IOException::class)

  30. fun execute(): Response

  31. /**

  32. * Schedules the request to be executed at some point in the future.

  33. *

  34. * The [dispatcher][OkHttpClient.dispatcher] defines when the request will run: usually

  35. * immediately unless there are several other requests currently being executed.

  36. *

  37. * This client will later call back `responseCallback` with either an HTTP response or a failure

  38. * exception.

  39. *

  40. * @throws IllegalStateException when the call has already been executed.

  41. */

  42. fun enqueue(responseCallback: Callback)

  43. /** Cancels the request, if possible. Requests that are already complete cannot be canceled. */

  44. fun cancel()

  45. /**

  46. * Returns true if this call has been either [executed][execute] or [enqueued][enqueue]. It is an

  47. * error to execute a call more than once.

  48. */

  49. fun isExecuted(): Boolean

  50. fun isCanceled(): Boolean

  51. /**

  52. * Returns a timeout that spans the entire call: resolving DNS, connecting, writing the request

  53. * body, server processing, and reading the response body. If the call requires redirects or

  54. * retries all must complete within one timeout period.

  55. *

  56. * Configure the client's default timeout with [OkHttpClient.Builder.callTimeout].

  57. */

  58. fun timeout(): Timeout

  59. /**

  60. * Create a new, identical call to this one which can be enqueued or executed even if this call

  61. * has already been.

  62. */

  63. public override fun clone(): Call

  64. fun interface Factory {

  65. fun newCall(request: Request): Call

  66. }

  67. }

很容易发现,Call是一个接口,并且,提供了很多待实现的方法。

在 Call 接口中,Factory 接口定义了一个方法:

fun newCall(request: Request): Call

这个方法接受一个 Request 对象作为参数,并返回一个 Call 对象。具体的实现由实现 Factory 接口的类来提供。而我们的OkHttClient也实现了这个接口。

所以,这就是为什么可以通过client可以调用newCall方法返回Call对象的原因。回到正轨,我们前面client.call最终是通过实现newCall方法拿到了Call对象,而newCall方法又是通过RealCall方法返回了一个Call对象, 所以我们需要去看RealCall到底做了什么。

下面贴出了RealCall的部分源码,我们可以看到,RealCall其实是实现了Call接口的,所以这里RealCall确实可以返回Call对象,同时它也实现了Call的抽象方法,比如execute(同步请求)、enqueue(异步请求)等等。

 
  1. class RealCall(

  2. val client: OkHttpClient,

  3. /** The application's original request unadulterated by redirects or auth headers. */

  4. val originalRequest: Request,

  5. val forWebSocket: Boolean

  6. ) : Call {

  7. override fun execute(): Response {

  8. check(executed.compareAndSet(false, true)) { "Already Executed" }

  9. timeout.enter()

  10. callStart()

  11. try {

  12. client.dispatcher.executed(this)

  13. return getResponseWithInterceptorChain()

  14. } finally {

  15. client.dispatcher.finished(this)

  16. }

  17. }

  18. override fun enqueue(responseCallback: Callback) {

  19. check(executed.compareAndSet(false, true)) { "Already Executed" }

  20. callStart()

  21. client.dispatcher.enqueue(AsyncCall(responseCallback))

  22. }

  23. @Throws(IOException::class)

  24. internal fun getResponseWithInterceptorChain(): Response {

  25. // Build a full stack of interceptors.

  26. val interceptors = mutableListOf<Interceptor>()

  27. interceptors += client.interceptors

  28. interceptors += RetryAndFollowUpInterceptor(client)

  29. interceptors += BridgeInterceptor(client.cookieJar)

  30. interceptors += CacheInterceptor(client.cache)

  31. interceptors += ConnectInterceptor

  32. if (!forWebSocket) {

  33. interceptors += client.networkInterceptors

  34. }

  35. interceptors += CallServerInterceptor(forWebSocket)

  36. val chain = RealInterceptorChain(

  37. call = this,

  38. interceptors = interceptors,

  39. index = 0,

  40. exchange = null,

  41. request = originalRequest,

  42. connectTimeoutMillis = client.connectTimeoutMillis,

  43. readTimeoutMillis = client.readTimeoutMillis,

  44. writeTimeoutMillis = client.writeTimeoutMillis

  45. )

  46. var calledNoMoreExchanges = false

  47. try {

  48. val response = chain.proceed(originalRequest)

  49. if (isCanceled()) {

  50. response.closeQuietly()

  51. throw IOException("Canceled")

  52. }

  53. return response

  54. } catch (e: IOException) {

  55. calledNoMoreExchanges = true

  56. throw noMoreExchanges(e) as Throwable

  57. } finally {

  58. if (!calledNoMoreExchanges) {

  59. noMoreExchanges(null)

  60. }

  61. }

  62. }

  63. }

val call = client.newCall(request)

好了,这里我们也分析出来我们是如何获得的call对象了。接下来,我们再去分析,它是如何进行同步请求和异步请求的。这里我们先分析异步请求。

异步请求 

 
  1. // 4.2调用call对象的异步请求方法

  2. call.enqueue(object : Callback {

  3. override fun onFailure(call: Call, e: IOException) {

  4. Log.d("a", "onFailure:") // 失败回调

  5. }

  6. override fun onResponse(call: Call, response: Response) {

  7. Log.d("b", "onResponse:") // 成功回调

  8. }

  9. })

 前面源码里面也看到,我们的RealCall对象也是实现了Call接口并且重写了里面的方法的。那么它具体是怎么执行我们的enqueue方法的呢?

 
  1. override fun enqueue(responseCallback: Callback) {

  2. check(executed.compareAndSet(false, true)) { "Already Executed" }

  3. callStart()

  4. client.dispatcher.enqueue(AsyncCall(responseCallback))

  5. }

首先,check,通过check来判断我们是否已经执行了一次enqueue方法了,因为call只允许你调用一次请求,使用完以后无法再重新调用,所以通过原子性判断操作,看我们是否已经执行过了,这里之前Java版的OkHttp源码并不是使用原子性操作来判断的,是用一个变量来判断是否已经有过一次请求了,所以这里其实是做了一个优化。

然后发现它调用一个callStart,这个方法其实是一个监听,里面有方法可以重写,比如网络开始丽连接的时候,DNS域名开始查询的时候等等。这里不做重点分析,感兴趣的可以看看源码,下面是不分源码。

重点来了:client.dispatcher.enqueue(AsyncCall(responseCallback)),这里出现了AsyncCall我们先看看它是什么。

AsyncCall 是 RealCall 的内部类, 它实现了 Runnable 接口,主要是为了能在线程池中去执行它的 run() 方法。

 
  1. internal inner class AsyncCall(

  2. private val responseCallback: Callback

  3. ) : Runnable {

  4. @Volatile var callsPerHost = AtomicInteger(0)

  5. private set

  6. fun reuseCallsPerHostFrom(other: AsyncCall) {

  7. // callPerHost代表了连接同一个host的连接数

  8. // 此连接数必须小于5

  9. this.callsPerHost = other.callsPerHost

  10. }

  11. val host: String

  12. get() = originalRequest.url.host

  13. val request: Request

  14. get() = originalRequest

  15. val call: RealCall

  16. get() = this@RealCall

  17. // 将asyncCall添加到线程池中去执行的方法

  18. fun executeOn(executorService: ExecutorService) {

  19. client.dispatcher.assertThreadDoesntHoldLock()

  20. var success = false

  21. try {

  22. // 线程池去执行当前AsyncCall对象的run方法

  23. executorService.execute(this)

  24. success = true

  25. } catch (e: RejectedExecutionException) {

  26. val ioException = InterruptedIOException("executor rejected")

  27. ioException.initCause(e)

  28. noMoreExchanges(ioException)

  29. responseCallback.onFailure(this@RealCall, ioException)

  30. } finally {

  31. if (!success) {

  32. // 收尾工作

  33. // 其实内部调用的是 promoteAndExecute()

  34. client.dispatcher.finished(this)

  35. }

  36. }

  37. }

  38. override fun run() {

  39. threadName("OkHttp ${redactedUrl()}") {

  40. var signalledCallback = false

  41. timeout.enter()

  42. try {

  43. // getResponseWithInterceptorChain() 获得请求的响应结果

  44. val response = getResponseWithInterceptorChain()

  45. signalledCallback = true

  46. // 请求成功的回调

  47. responseCallback.onResponse(this@RealCall, response)

  48. } catch (e: IOException) {

  49. if (signalledCallback) {

  50. Platform.get().log("Callback failure for ${toLoggableString()}", Platform.INFO, e)

  51. } else {

  52. responseCallback.onFailure(this@RealCall, e)

  53. }

  54. } catch (t: Throwable) {

  55. cancel()

  56. if (!signalledCallback) {

  57. val canceledException = IOException("canceled due to $t")

  58. canceledException.addSuppressed(t)

  59. // 请求失败的回调

  60. responseCallback.onFailure(this@RealCall, canceledException)

  61. }

  62. throw t

  63. } finally {

  64. // 进行收尾工作

  65. // 相比同步请求的finished方法,这儿更重要

  66. client.dispatcher.finished(this)

  67. }

  68. }

  69. }

  70. }

可以看到,我们的AsyncCall实现了Runnable方法并且实现了run方法。Run方法里面的getResponseWithInterceptorChain就是我们后续的拦截器的调用了。

现在我们再去分析client.dispatcher.enqueue(AsyncCall(responseCallback)),我们可以看看dispatcher的源码,这块源码里面的注释已经解释的很清楚了。主要逻辑就是,对AsyncCall对象进行挑选,将它们放入runningAsyncCalls中。

Dispatcher分发器主要功能:内部维护队列与线程池,完成请求调配。

 
  
  1. //异步请求同时存在的最大请求

  2. private int maxRequests = 64;

  3. //异步请求同一域名同时存在的最大请求

  4. private int maxRequestsPerHost = 5;

  5. //闲置任务(没有请求时可执行一些任务,由使用者设置)

  6. private @Nullable Runnable idleCallback;

  7. //异步请求使用的线程池

  8. private @Nullable ExecutorService executorService;

  9. //异步请求等待执行队列

  10. private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

  11. //异步请求正在执行队列

  12. private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

  13. //同步请求正在执行队列

  14. private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

 
  1. // Dispatcher.kt

  2. // 准备执行的异步请求队列

  3. private val readyAsyncCalls = ArrayDeque<AsyncCall>()

  4. // 正在执行的异步请求队列

  5. private val runningAsyncCalls = ArrayDeque<AsyncCall>()

  6. internal fun enqueue(call: AsyncCall) {

  7. synchronized(this) {

  8. // 加当前asyncCall加到准备执行的异步请求队列中

  9. readyAsyncCalls.add(call)

  10. if (!call.call.forWebSocket) {

  11. // 这里是得到连接同一个 host 的请求数

  12. val existingCall = findExistingCallWithHost(call.host)

  13. if (existingCall != null) call.reuseCallsPerHostFrom(existingCall)

  14. }

  15. }

  16. // dispatcher进行分发call任务的方法

  17. promoteAndExecute()

  18. }

  19. // 关键方法,dispatcher进行任务分发的方法

  20. // 进行收尾工作时,也是调用的它

  21. private fun promoteAndExecute(): Boolean {

  22. this.assertThreadDoesntHoldLock()

  23. // 需要开始执行的任务集合

  24. val executableCalls = mutableListOf<AsyncCall>()

  25. val isRunning: Boolean

  26. synchronized(this) {

  27. val i = readyAsyncCalls.iterator()

  28. // 迭代等待执行异步请求

  29. while (i.hasNext()) {

  30. val asyncCall = i.next()

  31. // 正在执行异步请求的总任务数不能大于64个

  32. // 否则直接退出这个循环,不再将请求加到异步请求队列中

  33. if (runningAsyncCalls.size >= this.maxRequests) break

  34. // 同一个host的请求数不能大于5

  35. // 否则直接跳过此call对象的添加,去遍历下一个asyncCall对象

  36. if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue

  37. i.remove()

  38. // 如果拿到了符合条件的asyncCall对象,就将其callPerHost值加1

  39. // callPerHost代表了连接同一个host的数量

  40. asyncCall.callsPerHost.incrementAndGet()

  41. // 加到需要开始执行的任务集合中

  42. executableCalls.add(asyncCall)

  43. // 将当前call加到正在执行的异步队列当中

  44. runningAsyncCalls.add(asyncCall)

  45. }

  46. isRunning = runningCallsCount() > 0

  47. }

  48. for (i in 0 until executableCalls.size) {

  49. // 遍历每一个集合中的asyncCall对象

  50. // 将其添加到线程池中,执行它的run方法

  51. val asyncCall = executableCalls[i]

  52. asyncCall.executeOn(executorService)

  53. }

  54. return isRunning

  55. }

现在我们通过 Dispatcher 将 AsyncCall 对象通过挑选,加到了线程池中。挑选的限制有两个:

1.当前执行的总请求数要小于64个。

2.对于连接的同一个host请求,要保证数量小于5。

现在,我们再回头看看将 AsyncCall 对象加到线程池后的一些细节吧!

 
  1. // Dispatcher.kt

  2. // 将asyncCall添加到线程池中去执行的方法

  3. fun executeOn(executorService: ExecutorService) {

  4. client.dispatcher.assertThreadDoesntHoldLock()

  5. var success = false

  6. try {

  7. // 这里是之前自定义了创建了一个ExecutorService

  8. executorService.execute(this)

  9. success = true

  10. } catch (e: RejectedExecutionException) {

  11. val ioException = InterruptedIOException("executor rejected")

  12. ioException.initCause(e)

  13. noMoreExchanges(ioException)

  14. responseCallback.onFailure(this@RealCall, ioException)

  15. } finally {

  16. if (!success) {

  17. // 这里也是会执行收尾工作

  18. client.dispatcher.finished(this)

  19. }

  20. }

  21. }

  22. @get:JvmName("executorService") val executorService: ExecutorService

  23. get() {

  24. if (executorServiceOrNull == null) {

  25. // !!这里的corePoolSize是 0

  26. // !!阻塞队列是 SynchronousQueue

  27. executorServiceOrNull = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS,

  28. SynchronousQueue(), threadFactory("$okHttpName Dispatcher", false))

  29. }

  30. return executorServiceOrNull!!

  31. }

我们先来看 executeOn() 方法,它的主要工作就是执行添加到线程池的 AsyncCall 对象的 run() 方法,去进行网络请求。其次我们目光移动到 finally 语句块,会发现每次执行完 run() 方法后,即完成网络请求后,都会去执行这个 finished() 方法。前面讲到过,内部其实是再次调用了 promoteAndExecute() 方法。那这是为什么呢?

还记得到我们从准备执行的异步队列中挑选一些 AsyncCall 对象拿到线程池中执行吗?如果记得,那你是否还记得我们是有挑选条件的,正因如此,可能在准备执行的异步请求队列中会有一些 AsyncCall 对象不满足条件仍然留在队列里!那我们难道最后就不执行这些网络请求了吗?当然不是!原来每完成一次网络请求就会再次触发 Dispatcher 去分发 AsyncCall 对象!原来如此。

 
  1. private fun promoteAndExecute(): Boolean {

  2. this.assertThreadDoesntHoldLock()

  3. val executableCalls = mutableListOf<AsyncCall>()

  4. val isRunning: Boolean

  5. synchronized(this) {

  6. val i = readyAsyncCalls.iterator()

  7. while (i.hasNext()) {

  8. val asyncCall = i.next()

  9. if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity.

  10. if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue // Host max capacity.

  11. i.remove()

  12. asyncCall.callsPerHost.incrementAndGet()

  13. executableCalls.add(asyncCall)

  14. runningAsyncCalls.add(asyncCall)

  15. }

  16. isRunning = runningCallsCount() > 0

  17. }

  18. for (i in 0 until executableCalls.size) {

  19. val asyncCall = executableCalls[i]

  20. asyncCall.executeOn(executorService)

  21. }

  22. return isRunning

  23. }

可以看到,这里会对我们准备队列里面的call进行筛选,此时如果满足条件,我们的call就会被筛选出来到运行队列去执行。

 

然后我们再来看看这里用到的线程池是一个什么样的线程池。在上面我贴出来的代码中可以看到,这个线程池的 corePoolSize 是 0BlockingQueue 是 SynchronousQueue,这样构建出来的线程池有什么特殊之处吗?

熟悉线程池的同学都应该知道,当任务数超过了 corePoolSize 就会将其加到阻塞队列当中。也就是说这些任务不会立马执行,而我们的网络请求可不想被阻塞着。

因此这里的 corePoolSize 就设置成了 0BlockingQueue 设置成 SynchronousQueue 也是类似道理,SynchronousQueue 是不储存元素的,只要提交的任务数小于最大线程数就会立刻新起线程去执行任务。

好了,我们的异步请求暂时先讲到这块,我们最终获得response是在我们RealCall对象重写的run方法里面去拿到的,还记得它的run方法里面的

          val response = getResponseWithInterceptorChain()

这块就是拦截器的内容了,这里先不说,我们先继续把同步的情况说完。

同步请求

 
  1. // 调用call对象的同步请求方法

  2. val response = call.execute()

 继续追溯源码,查看execute方法。

 
  1. override fun execute(): Response {

  2. check(executed.compareAndSet(false, true)) { "Already Executed" }

  3. timeout.enter()

  4. callStart()

  5. try {

  6. client.dispatcher.executed(this)

  7. return getResponseWithInterceptorChain()

  8. } finally {

  9. client.dispatcher.finished(this)

  10. }

  11. }

 这块的check、callStart基本都是和异步请求一样的逻辑。由于是同步队列,无需考虑其他的,将任务加到队列里就好。

 
  1. override fun execute(): Response {

  2. // 一个call对象只能执行一次execute方法

  3. // 这里用CAS思想进行比较,可以提高效率

  4. check(executed.compareAndSet(false, true)) { "Already Executed" }

  5. timeout.enter()

  6. // 这里主要是个监听器,表示开始进行网络请求了

  7. callStart()

  8. // 重点关注这块

  9. try {

  10. // 通过分发器进行任务分发

  11. // 其实这里还体现不出分发器的效果,仅仅是将当前请求加入到一个同步队列当中

  12. client.dispatcher.executed(this)

  13. // 通过 getResponseWithInterceptorChain() 获得相应结果

  14. return getResponseWithInterceptorChain()

  15. } finally {

  16. // 完成一些收尾工作,在同步请求中,几乎没什么用

  17. client.dispatcher.finished(this)

  18. }

  19. }

总结一下整个 okhttp 网络请求的整个过程。

首先通过我们通过 构造者 的方式构建好了 OkHttpClient 和 Request 对象,然后调用 OkHttpClient 对象的 newCall() 方法得到一个 RealCall 对象,最后再调用其 execute() 或者 enqueue() 方法进行同步或者异步请求。

然后如果是同步请求,Dispatacher 分发器去只是简单的将其加入到正在执行的同步请求队列中做一个标记,如果是异步请求就会根据 两个条件 去筛选合适的请求,并将其发送给一个特定的线程池中去进行网络请求,最后通过 getResponseWithInterceptorChain() 得到最终结果。

  你回过头再看看,是不是和上面的使用流程图基本上一样的呢? 

 拦截器

getResponseWithInterceptorChain是怎么拿到我们最终的结果呢?这里我们先学一下相关的前置知识。

首先,我们需要了解什么是责任链模式。

对象行为型模式,为请求创建了一个接收者对象的链,在处理请求的时候执行过滤(各司其职)。 责任链上的处理者负责处理请求,客户只需要将请求发送到责任链即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了

如果你需要点外卖,你只需要去美团下单就好了,不需要做其他事情,美味就来了,干净又卫生。

这里先我们介绍一下我们在网络请求中涉及的五大拦截器。

  1. RetryAndFollowUpInterceptor:请求失败自动重试,如果 DNS 设置了多个ip地址会自动重试其余ip地址。
  2. BridgeInterceptor:会补全我们请求中的请求头,例如HostCookieAccept-Encoding等。
  3. CacheInterceptor:会选择性的将响应结果进行保存,以便下次直接读取,不再需要再向服务器索要数据。
  4. ConnectInterceptor:建立连接并得到对应的socket;管理连接池,从中存取连接,以便达到连接复用的目的。
  5. CallServerInterceptor:与服务器建立连接,具体进行网络请求,并将结果逐层返回的地方。

我们的拦截器就是使用了这是模式,由五大拦截器一层层分发下去,最后得到结果再一层层返回上来。 

现在,我们开始正式分析, getResponseWithInterceptorChain

 
  1. // 五大拦截器的起始入口

  2. @Throws(IOException::class)

  3. internal fun getResponseWithInterceptorChain(): Response {

  4. // 用一个集合保存所有的拦截器

  5. val interceptors = mutableListOf<Interceptor>()

  6. // 这个interceptor就是我们自己可以加的第一个拦截器

  7. // 因为位于所有拦截器的第一个,与我们的应用直接相连

  8. // 因此这个拦截器又被称为 Application Interceptor

  9. interceptors += client.interceptors

  10. // 重试重定向拦截器

  11. interceptors += RetryAndFollowUpInterceptor(client)

  12. // 桥接拦截器

  13. interceptors += BridgeInterceptor(client.cookieJar)

  14. // 缓存拦截器

  15. interceptors += CacheInterceptor(client.cache)

  16. // 连接拦截器

  17. interceptors += ConnectInterceptor

  18. if (!forWebSocket) {

  19. // 这个interceptor也是我们自己可以加的一个拦截器

  20. // 因为位于真正请求返回结果的拦截器前面,可以拿到服务器返回的最原始的结果

  21. // 因此这个拦截器又被称为 Network Interceptor

  22. interceptors += client.networkInterceptors

  23. }

  24. interceptors += CallServerInterceptor(forWebSocket)

  25. // 构建RealInterceptorChain对象,我们正是通过此对象将请求逐层往下传递的

  26. val chain = RealInterceptorChain(

  27. call = this,

  28. interceptors = interceptors,

  29. index = 0,

  30. exchange = null,

  31. request = originalRequest,

  32. connectTimeoutMillis = client.connectTimeoutMillis,

  33. readTimeoutMillis = client.readTimeoutMillis,

  34. writeTimeoutMillis = client.writeTimeoutMillis

  35. )

  36. var calledNoMoreExchanges = false

  37. try {

  38. // 调用RealInterceptorChain的proceed()方法,将请求向下一个连接器传递

  39. val response = chain.proceed(originalRequest)

  40. if (isCanceled()) {

  41. response.closeQuietly()

  42. throw IOException("Canceled")

  43. }

  44. // 放回响应结果

  45. return response

  46. } catch (e: IOException) {

  47. calledNoMoreExchanges = true

  48. throw noMoreExchanges(e) as Throwable

  49. } finally {

  50. if (!calledNoMoreExchanges) {

  51. noMoreExchanges(null)

  52. }

  53. }

  54. }

从这个方法中我们大概可以总结出,它将所有的拦截器包括用户自定义的拦截器全部通过一个集合保存了下来,然后构建出了 RealInterceptorChain 对象,并调用其 proceed() 方法开始了拦截器逐层分发工作。

那么它是怎么做到逐层分发的呢?其实很简单,每一个拦截器中都会通过 proceed() 方法再构建一个 RealInterceptorChain 对象,然后调用 intercpt去执行下个拦截器中的任务,如此循环,最终走到最后一个拦截器后退出。

 
  1. // RealInterceptorChain.kt -----> 实现了 Chain 接口

  2. override fun proceed(request: Request): Response {

  3. // 检查是否走完了所有的拦截器,是则退出

  4. check(index < interceptors.size

  5. ...

  6. // 这个方法就是再次构建了 RealInterceptorChain 对象 ==> next

  7. // 去执行下个拦截器中的任务

  8. val next = copy(index = index + 1, request = request)// 这个方法内部就一行代码 new RealInterceptorChain()

  9. val interceptor = interceptors[index]

  10. @Suppress("USELESS_ELVIS")

  11. // 通过调用intercept(next)去执行下一个拦截器中的任务

  12. val response = interceptor.intercept(next) ?: throw NullPointerException(

  13. "interceptor $interceptor returned null")

  14. ...

  15. // 将结果放回到上一个拦截器中

  16. return response

  17. }

以上我们搞清楚了拦截器是如何一步一步往下传递任务,并逐层往上返回结果的,现在我们来具体看看每个拦截器都做了什么事情。 

RetryAndFollowUpInterceptor拦截器

 
  1. // RetryAndFollowUpInterceptor.kt

  2. // 所有拦截求都实现了 Interceptor 接口

  3. override fun intercept(chain: Interceptor.Chain): Response {

  4. val realChain = chain as RealInterceptorChain

  5. var request = chain.request

  6. val call = realChain.call

  7. var followUpCount = 0

  8. var priorResponse: Response? = null

  9. var newExchangeFinder = true

  10. var recoveredFailures = listOf<IOException>()

  11. // 这是个死循环,意思就是如果请求失败就需要一直重试,直到主动退出循环(followUpCount>20)

  12. while (true) {

  13. // ExchangeFinder: 获取连接 ---> ConnectInterceptor中使用

  14. call.enterNetworkInterceptorExchange(request, newExchangeFinder)

  15. // 响应结果

  16. var response: Response

  17. var closeActiveExchange = true

  18. try {

  19. if (call.isCanceled()) {

  20. throw IOException("Canceled")

  21. }

  22. try {

  23. // 调用下一个拦截器,即 BridgeInterceptor

  24. // 整个请求可能会失败,需要捕获然后重试重定向,因此有一个try catch

  25. response = realChain.proceed(request)

  26. newExchangeFinder = true

  27. } catch (e: RouteException) { //1.进行重试

  28. // 1.1 路线异常,检查是否需要重试

  29. if (!recover(e.lastConnectException, call, request, requestSendStarted = false)) {

  30. throw e.firstConnectException.withSuppressed(recoveredFailures)

  31. } else {

  32. recoveredFailures += e.firstConnectException

  33. }

  34. newExchangeFinder = false

  35. // 失败继续重试

  36. continue

  37. } catch (e: IOException) {

  38. // 1.2 IO异常 HTTP2才会有ConnectionShutdownException 代表连接中断

  39. //如果是因为IO异常,那么requestSendStarted=true (若是HTTP2的连接中断异常仍然为false)

  40. if (!recover(e, call, request, requestSendStarted = e !is ConnectionShutdownException)) {

  41. throw e.withSuppressed(recoveredFailures)

  42. } else {

  43. recoveredFailures += e

  44. }

  45. newExchangeFinder = false

  46. // 失败继续重试

  47. continue

  48. }

  49. // priorResponse:上一次请求的响应

  50. if (priorResponse != null) {

  51. response = response.newBuilder()

  52. .priorResponse(priorResponse.newBuilder()

  53. .body(null)

  54. .build())

  55. .build()

  56. }

  57. val exchange = call.interceptorScopedExchange

  58. // 2.根据返回的response进行重定向,构建新的Request对象

  59. val followUp = followUpRequest(response, exchange)

  60. // 2.1 followUp为空,代表没有重定向,直接返回结果response

  61. if (followUp == null) {

  62. if (exchange != null && exchange.isDuplex) {

  63. call.timeoutEarlyExit()

  64. }

  65. closeActiveExchange = false

  66. return response

  67. }

  68. // 2.2 followUp不为空,但是body中设置了只能请求一次(默认),返回重定向后的结果response

  69. val followUpBody = followUp.body

  70. if (followUpBody != null && followUpBody.isOneShot()) {

  71. closeActiveExchange = false

  72. return response

  73. }

  74. // 重试次数大于20次,抛出异常

  75. if (++followUpCount > MAX_FOLLOW_UPS) {

  76. throw ProtocolException("Too many follow-up requests: $followUpCount")

  77. }

  78. // 将之前重定向后的Request对象赋值给request进行重新请求

  79. request = followUp

  80. priorResponse = response

  81. } finally {

  82. call.exitNetworkInterceptorExchange(closeActiveExchange)

  83. }

  84. }

  85. }

简单来说,RetryAndFollowUpInterceptor拦截器帮我们干了两件事。第一是重试,第二是重定向。

✅ 我们先来看看什么情况下它会进行重试。

 
  1. // RetryAndFollowUpInterceptor.kt

  2. // 这个方法就是来判断当前请求是否需要重试的

  3. private fun recover(

  4. e: IOException,

  5. call: RealCall,

  6. userRequest: Request,

  7. requestSendStarted: Boolean

  8. ): Boolean {

  9. // 构建OkHttpClient时配置不重试,则返回false

  10. if (!client.retryOnConnectionFailure) return false

  11. // 返回false

  12. // 1、如果是IO异常(非http2中断异常)表示请求可能发出

  13. // 2、如果请求体只能被使用一次(默认为false)

  14. if (requestSendStarted && requestIsOneShot(e, userRequest)) return false

  15. // 返回false

  16. // 协议异常、IO中断异常(除Socket读写超时之外),ssl认证异常

  17. if (!isRecoverable(e, requestSendStarted)) return false

  18. // 无更多的路线,返回false

  19. if (!call.retryAfterFailure()) return false

  20. // 以上情况都不是,则返回true 表示可以重试

  21. return true

  22. }

✅ 再来看看如何判断是否需要重定向的。

 
  1. @Throws(IOException::class)

  2. private fun followUpRequest(userResponse: Response, exchange: Exchange?): Request? {

  3. val route = exchange?.connection?.route()

  4. val responseCode = userResponse.code

  5. val method = userResponse.request.method

  6. when (responseCode) {

  7. // 407 代理需要授权,通过proxyAuthenticator获得request,向其中添加请求头 Proxy-Authorization

  8. // 然后构建一个新的request对象返回出去,准备再次请求

  9. HTTP_PROXY_AUTH -> {

  10. val selectedProxy = route!!.proxy

  11. if (selectedProxy.type() != Proxy.Type.HTTP) {

  12. throw ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy")

  13. }

  14. return client.proxyAuthenticator.authenticate(route, userResponse)

  15. }

  16. // 401 服务器请求需授权,通过authenticator获得到了Request,添加Authorization请求头

  17. // 然后构建一个新的request对象返回出去,准备再次请求

  18. HTTP_UNAUTHORIZED -> return client.authenticator.authenticate(route, userResponse)

  19. // 返回的响应码是3xx,这就准备进行重定向,构建新的Request对象

  20. HTTP_PERM_REDIRECT, HTTP_TEMP_REDIRECT, HTTP_MULT_CHOICE, HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_SEE_OTHER -> {

  21. return buildRedirectRequest(userResponse, method)

  22. }

  23. // 408 请求超时

  24. HTTP_CLIENT_TIMEOUT -> {

  25. // 用户设置是否可以进行重试(默认允许)

  26. if (!client.retryOnConnectionFailure) {

  27. return null

  28. }

  29. val requestBody = userResponse.request.body

  30. if (requestBody != null && requestBody.isOneShot()) {

  31. return null

  32. }

  33. val priorResponse = userResponse.priorResponse

  34. // 如果上次也是因为408导致重试,这次请求又返回的408,则不会再去重试了,直接返回null

  35. if (priorResponse != null && priorResponse.code == HTTP_CLIENT_TIMEOUT) {

  36. return null

  37. }

  38. // 服务器返回的 Retry-After:0 或者未响应Retry-After就不会再次去请求

  39. if (retryAfter(userResponse, 0) > 0) {

  40. return null

  41. }

  42. // 返回当前的request对象,准备再次请求

  43. return userResponse.request

  44. }

  45. // 503 服务不可用

  46. HTTP_UNAVAILABLE -> {

  47. val priorResponse = userResponse.priorResponse

  48. // 和408相似,如果两次都是503导致请求重试,那么这次就不会再重试了,直接返回null

  49. if (priorResponse != null && priorResponse.code == HTTP_UNAVAILABLE) {

  50. return null

  51. }

  52. // 服务端返回的有Retry-After: 0,则立即重试

  53. if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {

  54. return userResponse.request

  55. }

  56. return null

  57. }

  58. // 421 当前客户端的IP地址连接到服务器的数量超过了服务器允许的范围

  59. HTTP_MISDIRECTED_REQUEST -> {

  60. val requestBody = userResponse.request.body

  61. if (requestBody != null && requestBody.isOneShot()) {

  62. return null

  63. }

  64. if (exchange == null || !exchange.isCoalescedConnection) {

  65. return null

  66. }

  67. // 使用另一个连接对象发起请求

  68. exchange.connection.noCoalescedConnections()

  69. return userResponse.request

  70. }

  71. else -> return null

  72. }

  73. }

BridgeInterceptor拦截器 

接下来,来到第二个拦截器 BridgeInterceptor。这个拦截器前面说过,主要就是用来补全请求头的,除此之外就是如果响应头中有Content-Encoding: gzip,则会用 GzipSource 进行解析。

 
  1. // BridgeInterceptor.kt

  2. class BridgeInterceptor(private val cookieJar: CookieJar) : Interceptor {

  3. @Throws(IOException::class)

  4. override fun intercept(chain: Interceptor.Chain): Response {

  5. val userRequest = chain.request()

  6. val requestBuilder = userRequest.newBuilder()

  7. // 这里没有什么多说的,就是补全请求头

  8. val body = userRequest.body

  9. if (body != null) {

  10. val contentType = body.contentType()

  11. if (contentType != null) {

  12. requestBuilder.header("Content-Type", contentType.toString())

  13. }

  14. val contentLength = body.contentLength()

  15. if (contentLength != -1L) {

  16. requestBuilder.header("Content-Length", contentLength.toString())

  17. requestBuilder.removeHeader("Transfer-Encoding")

  18. } else {

  19. requestBuilder.header("Transfer-Encoding", "chunked")

  20. requestBuilder.removeHeader("Content-Length")

  21. }

  22. }

  23. if (userRequest.header("Host") == null) {

  24. requestBuilder.header("Host", userRequest.url.toHostHeader())

  25. }

  26. if (userRequest.header("Connection") == null) {

  27. requestBuilder.header("Connection", "Keep-Alive")

  28. }

  29. var transparentGzip = false

  30. if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {

  31. transparentGzip = true

  32. requestBuilder.header("Accept-Encoding", "gzip")

  33. }

  34. val cookies = cookieJar.loadForRequest(userRequest.url)

  35. if (cookies.isNotEmpty()) {

  36. requestBuilder.header("Cookie", cookieHeader(cookies))

  37. }

  38. if (userRequest.header("User-Agent") == null) {

  39. requestBuilder.header("User-Agent", userAgent)

  40. }

  41. // 去调用下一个拦截器,并得到响应结果

  42. val networkResponse = chain.proceed(requestBuilder.build())

  43. cookieJar.receiveHeaders(userRequest.url, networkResponse.headers)

  44. val responseBuilder = networkResponse.newBuilder()

  45. .request(userRequest)

  46. // 根据响应头中的 Content-Encoding,判断是否需要gzip解析

  47. if (transparentGzip &&

  48. "gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) &&

  49. networkResponse.promisesBody()) {

  50. val responseBody = networkResponse.body

  51. if (responseBody != null) {

  52. val gzipSource = GzipSource(responseBody.source())

  53. val strippedHeaders = networkResponse.headers.newBuilder()

  54. .removeAll("Content-Encoding")

  55. .removeAll("Content-Length")

  56. .build()

  57. responseBuilder.headers(strippedHeaders)

  58. val contentType = networkResponse.header("Content-Type")

  59. // 进行gzip解析

  60. responseBuilder.body(RealResponseBody(contentType, -1L, gzipSource.buffer()))

  61. }

  62. }

  63. return responseBuilder.build()

  64. }

桥接拦截器其实工作内容也很简单,在请求之前,向我们的请求头中添加必要的参数,然后拿到请求的响应后,根据响应头中的参数去判断是否需要 gzip 解析,如果需要则用 GzipSource 去解析就好了。 

CacheInterceptor拦截器

在讲 CacheInterceptor 拦截器之前,我们先来了解一下 HTTP的缓存规则。 我们按照其行为将其分为两大类:强缓存和协商缓存。(这块可以去看小林Coding里面的,很详细)

1️⃣强缓存:浏览器并不会将请求发送给服务器。强缓存是利用 http 的返回头中的 Expires 或者 Cache-Control 两个字段来控制的,用来表示资源的缓存时间。

2️⃣协商缓存:浏览器会将请求发送至服务器。服务器根据 http 头信息中的 Last-Modify/If-Modify-Since 或 Etag/If-None-Match 来判断是否命中协商缓存。如果命中,则 http 返回码为 304 ,客户端从本地缓存中加载资源。

 
  1. // CacheInterceptor.kt

  2. @Throws(IOException::class)

  3. override fun intercept(chain: Interceptor.Chain): Response {

  4. val call = chain.call()

  5. val cacheCandidate = cache?.get(chain.request())

  6. val now = System.currentTimeMillis()

  7. val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()

  8. // 代表需要发起请求

  9. val networkRequest = strategy.networkRequest

  10. // 代表直接使用本地缓存

  11. val cacheResponse = strategy.cacheResponse

  12. ...

  13. // networkRequest 和 cacheResponse 都是null

  14. // 说明服务器要求使用缓存,但是本地没有缓存,直接失败

  15. if (networkRequest == null && cacheResponse == null) {

  16. return Response.Builder()

  17. .request(chain.request())

  18. .protocol(Protocol.HTTP_1_1)

  19. .code(HTTP_GATEWAY_TIMEOUT)

  20. .message("Unsatisfiable Request (only-if-cached)")

  21. .body(EMPTY_RESPONSE)// 构建一个空的response返回过去

  22. .sentRequestAtMillis(-1L)

  23. .receivedResponseAtMillis(System.currentTimeMillis())

  24. .build()

  25. }

  26. // networkRequest为null cacheResponse不为null

  27. // 说明使用强缓存,成功

  28. if (networkRequest == null) {

  29. return cacheResponse!!.newBuilder()

  30. .cacheResponse(stripBody(cacheResponse))

  31. .build().also {

  32. listener.cacheHit(call, it)

  33. }

  34. }

  35. ...

  36. var networkResponse: Response? = null

  37. try {

  38. // 走到这里说明需要请求一次,判断是协商缓存还是重新去服务器上获取资源

  39. // 因此 调用下一个拦截器去继续请求

  40. networkResponse = chain.proceed(networkRequest)

  41. } finally {

  42. if (networkResponse == null && cacheCandidate != null) {

  43. cacheCandidate.body?.closeQuietly()

  44. }

  45. }

  46. // 协商缓存

  47. // 如果我们本地有缓存,并且服务器放回给我们304响应码,直接使用本地的缓存

  48. if (cacheResponse != null) {

  49. if (networkResponse?.code == HTTP_NOT_MODIFIED) {

  50. val response = cacheResponse.newBuilder()

  51. .headers(combine(cacheResponse.headers, networkResponse.headers))

  52. .sentRequestAtMillis(networkResponse.sentRequestAtMillis)

  53. .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis)

  54. .cacheResponse(stripBody(cacheResponse))

  55. .networkResponse(stripBody(networkResponse))

  56. .build()

  57. networkResponse.body!!.close()

  58. return response

  59. ...

  60. } else {

  61. cacheResponse.body?.closeQuietly()

  62. }

  63. }

  64. // 走到这,说明响应码是200 表示我们需要用这次新请求的资源

  65. val response = networkResponse!!.newBuilder()

  66. .cacheResponse(stripBody(cacheResponse))

  67. .networkResponse(stripBody(networkResponse))

  68. .build()

  69. if (cache != null) {

  70. if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {

  71. // 将本次最新得到的响应存到cache中去

  72. val cacheRequest = cache.put(response)

  73. return cacheWritingResponse(cacheRequest, response).also {

  74. }

  75. }

  76. ...

  77. }

  78. // 将这次新请求的资源返回给上一层拦截器

  79. return response

  80. }

⚡ 总结一下缓存拦截器处理缓存的流程:首先得到 RealInterceptorChain 对象,然后通过它再得到两个很重要的对象:networkRequest 和 cacheResponse 。networkRequest 代表去发起一个网络请求, cacheResponse 代表使用本地缓存。通过这两个对象是否为 null来判断此次请求是使用直接缓存,还是去请求新的资源,还是去使用协商缓存。最后就是会更新缓存,把每次新请求的资源都重新保存至 cache 中。

ConnectInterceptor拦截器

连接拦截器主要就是做建立连接和连接复用的工作,它会从连接池中取出符合条件的连接,以免重复创建,从而提升请求效率。

 
  1. object ConnectInterceptor : Interceptor {

  2. @Throws(IOException::class)

  3. override fun intercept(chain: Interceptor.Chain): Response {

  4. val realChain = chain as RealInterceptorChain

  5. // 获取连接 Exchange:数据交换(封装了连接)

  6. val exchange = realChain.call.initExchange(chain)

  7. val connectedChain = realChain.copy(exchange = exchange)

  8. // 继续调用下一个拦截器去请求数据

  9. return connectedChain.proceed(realChain.request)

  10. }

  11. }

可以看到,这个连接拦截器中的代码比较少,主要的逻辑都在 initExchange() 方法当中,这个方法的作用就是拿到一个连接对象建立连接,这里我们可以看看initExchange的源码。

通过RealCall的initExchange(chain)创建一个Exchange对象,其中会打开与目标服务器的链接, 并调用 Chain.proceed()方法进入下一个拦截器。 initExchange()方法中会先通过 ExchangeFinder 尝试去 RealConnectionPool 中寻找已存在的连接,未找到则会重新创建一个RealConnection 并开始连接, 然后将其存入RealConnectionPool,现在已经准备好了RealConnection 对象,然后通过请求协议创建不同的ExchangeCodec 并返回,返回的ExchangeCodec正是创建Exchange对象的一个参数。 ConnectInterceptor的代码很简单,主要的功能就是初始化RealCall的Exchange。这个Exchange的功能就是基于RealConnection+ExchangeCodec进行数据交换。

 
  1. /**

  2. * 初始化并获取一个新的或池化的连接,用于执行即将到来的请求和响应。

  3. */

  4. internal fun initExchange(chain: RealInterceptorChain): Exchange {

  5. synchronized(this) {

  6. // 确保仍然期待更多的交换,且资源未被释放

  7. check(expectMoreExchanges) { "已释放" }

  8. // 确保响应体未打开

  9. check(!responseBodyOpen)

  10. // 确保请求体未打开

  11. check(!requestBodyOpen)

  12. }

  13. // 获取 ExchangeFinder 实例

  14. val exchangeFinder = this.exchangeFinder!!

  15. // 使用 ExchangeFinder 查找适合的编解码器

  16. val codec = exchangeFinder.find(client, chain)

  17. // 创建 Exchange 实例,包括当前对象、事件监听器、ExchangeFinder 和编解码器

  18. val result = Exchange(this, eventListener, exchangeFinder, codec)

  19. // 将创建的 Exchange 实例设置为拦截器范围的 Exchange 和主 Exchange

  20. this.interceptorScopedExchange = result

  21. this.exchange = result

  22. synchronized(this) {

  23. // 标记请求体和响应体为已打开状态

  24. this.requestBodyOpen = true

  25. this.responseBodyOpen = true

  26. }

  27. // 如果请求已取消,则抛出 IOException

  28. if (canceled) throw IOException("请求已取消")

  29. // 返回初始化后的 Exchange 实例

  30. return result

  31. }

CallServerInterceptor拦截器 

 
  1. // CallServerInterceptor.kt

  2. @Throws(IOException::class)

  3. override fun intercept(chain: Interceptor.Chain): Response {

  4. val realChain = chain as RealInterceptorChain

  5. val exchange = realChain.exchange!!

  6. val request = realChain.request

  7. val requestBody = request.body

  8. val sentRequestMillis = System.currentTimeMillis()

  9. // 将请求头写入缓存中

  10. exchange.writeRequestHeaders(request)

  11. var invokeStartEvent = true

  12. var responseBuilder: Response.Builder? = null

  13. if (HttpMethod.permitsRequestBody(request.method) && requestBody != null) {

  14. // 大容量请求体会带有 Expect: 100-continue 字段,服务器识别同意后,才能继续发送请求给服务端

  15. if ("100-continue".equals(request.header("Expect"), ignoreCase = true)) {

  16. // 与服务器进行请求

  17. exchange.flushRequest()

  18. responseBuilder = exchange.readResponseHeaders(expectContinue = true)

  19. exchange.responseHeadersStart()

  20. invokeStartEvent = false

  21. }

  22. if (responseBuilder == null) {

  23. if (requestBody.isDuplex()) {

  24. // Prepare a duplex body so that the application can send a request body later.

  25. exchange.flushRequest()

  26. val bufferedRequestBody = exchange.createRequestBody(request, true).buffer()

  27. requestBody.writeTo(bufferedRequestBody)

  28. } else {

  29. // 大部分情况都是走这里,通过IO流把响应结果写入response中

  30. val bufferedRequestBody = exchange.createRequestBody(request, false).buffer()

  31. requestBody.writeTo(bufferedRequestBody)

  32. bufferedRequestBody.close()

  33. }

  34. } else {

  35. exchange.noRequestBody()

  36. if (!exchange.connection.isMultiplexed) {

  37. // 没有响应 Expect:100 continue则阻止此连接得到复用,并且会关闭相关的socket

  38. exchange.noNewExchangesOnConnection()

  39. }

  40. }

  41. } else {

  42. exchange.noRequestBody()

  43. }

  44. ...

  45. var response = responseBuilder

  46. .request(request)

  47. .handshake(exchange.connection.handshake())

  48. .sentRequestAtMillis(sentRequestMillis)

  49. .receivedResponseAtMillis(System.currentTimeMillis())

  50. .build()

  51. var code = response.code

  52. if (code == 100) {

  53. // 返回100 表示接收大请求体请求 继续发送请求体

  54. // 得到response后返回结果

  55. responseBuilder = exchange.readResponseHeaders(expectContinue = false)!!

  56. // 构建响应体

  57. response = responseBuilder

  58. .request(request)

  59. .handshake(exchange.connection.handshake())

  60. .sentRequestAtMillis(sentRequestMillis)

  61. .receivedResponseAtMillis(System.currentTimeMillis())

  62. .build()

  63. code = response.code

  64. }

  65. response = if (forWebSocket && code == 101) {

  66. // 如果状态码是101并且是webSocket就返回空的response

  67. response.newBuilder()

  68. .body(EMPTY_RESPONSE)

  69. .build()

  70. } else {

  71. response.newBuilder()

  72. .body(exchange.openResponseBody(response))

  73. .build()

  74. }

  75. return response

  76. }

在 okhttp 中,面对比较大的请求体时,会先去询问服务器是否接收此请求体,如果服务器接收并返回响应码 200,则 okhttp 继续发送请求体,否则就直接返回给客户端。如果服务器忽略此请求,则不会响应,最后客户端会超时抛出异常。 

当然,如果你也可以自定义拦截器,在创建Client对象的时候,提供了对应的方法的。

拦截器这块的内容我目前感觉掌握的一般,这块的内容基本上参考掘金的一篇文章:传送门

好啦,以上就是OkHttp的核心代码剖析,欢迎大家和我一起在评论区探讨OkHttp的相关内容,笔者后续也会更新一些其他热门框架的源码剖析,喜欢的话可以留个关注,我还有很多技术文章or分享文章会不定时分享。

  • 30
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值