OKhttp源码的简单分析

OKhttp源码的简单分析

源码分析基于okhttp4.1.0,代码全部为kotlin。

先看okhttp的基本使用

val okHttpClient = OkHttpClient()
val request = Request.Builder()
    .url(address)
    .build()
//异步
okHttpClient.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {

    }

    override fun onResponse(call: Call, response: Response) {
    }
})
//同步
var response = okHttpClient.newCall(request).execute().body?.string()

发起请求的过程

不管是异步还是同步都是通过 OkHttpClient 对象来创建一个 call 来发起请求,OkHttpClient 是通过 Builder 模式来创建:

constructor() : this(Builder())

其中包含了 dispatcher 调度器、connectionPool 链接池、interceptors 过滤器等参数。

image-20191026192112318

Call 是一个接口,代表着一次请求, newCall 内有调用了又创建了一个RealCall

/** Prepares the [request] to be executed at some point in the future. */
override fun newCall(request: Request): Call {
  return RealCall.newRealCall(this, request, forWebSocket = false)
}

companion object {
  fun newRealCall(
    client: OkHttpClient,
    originalRequest: Request,
    forWebSocket: Boolean
  ): RealCall {
    // Safely publish the Call instance to the EventListener.
    return RealCall(client, originalRequest, forWebSocket).apply {
      transmitter = Transmitter(client, this)
    }
  }
}

internal class RealCall private constructor(
  val client: OkHttpClient,
  /** The application's original request unadulterated by redirects or auth headers. */
  val originalRequest: Request,
  val forWebSocket: Boolean
) : Call 

所以这里可以看到不管是异步还是同步都是通过 RealCall 来发起的请求,RealCall 通过 clientRequest 来创建。回到上面查看发起请求的方法,先看 execute 同步请求

//发起同步请求
override fun execute(): Response {
  synchronized(this) {
    //检查此请求是否已经执行过
    check(!executed) { "Already Executed" }
    executed = true
  }
  // 开启请求超时倒计时
  transmitter.timeoutEnter()
  // 开启请求的事件监听
  transmitter.callStart()
  try {
    //将此请求加入到调度器
    client.dispatcher.executed(this)
    //获取请求结果
    return getResponseWithInterceptorChain()
  } finally {
    //此次请求结束 从调度器中移除
    client.dispatcher.finished(this)
  }
}

getResponseWithInterceptorChain 方法内的具体请求流程暂时不看,只摸清发起请求的流程。查看调度器

/** Ready async calls in the order they'll be run. */
private val readyAsyncCalls = ArrayDeque<AsyncCall>()

/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private val runningAsyncCalls = ArrayDeque<AsyncCall>()

/** Running synchronous calls. Includes canceled calls that haven't finished yet. */
private val runningSyncCalls = ArrayDeque<RealCall>()

/** Used by `Call#execute` to signal it is in-flight. */
@Synchronized internal fun executed(call: RealCall) {
  runningSyncCalls.add(call)
}

/** Used by `AsyncCall#run` to signal completion. */
internal fun finished(call: AsyncCall) {
  call.callsPerHost().decrementAndGet()
  finished(runningAsyncCalls, call)
}

在请求开始和请求结束后会将这个请求从runningSyncCalls对列中加入和移除,调度器中有三个对列,分别是准备请求的异步请求readyAsyncCalls,正在执行的异步请求runningAsyncCalls和正在执行的同步请求runningSyncCalls

接下来看异步enqueue请求

override fun enqueue(responseCallback: Callback) {
  synchronized(this) {
    check(!executed) { "Already Executed" }
    executed = true
  }
  transmitter.callStart()
  client.dispatcher.enqueue(AsyncCall(responseCallback))
}

在异步请求中,加入调度器的并不是 RealCall,而是 AsyncCallAsyncCallRealCall的内部类。虽然叫Call但是发现其实并不是一个和 RealCall 一样实现了Call接口的类,而是一个Runnable

internal inner class AsyncCall(
  private val responseCallback: Callback
) : Runnable {

  fun executeOn(executorService: ExecutorService) {
    //代码省略
  }

  override fun run() {
    //代码省略
  }
}

回到上面查看调度器的enqueue方法

internal fun enqueue(call: AsyncCall) {
  synchronized(this) {
    //加入对列
    readyAsyncCalls.add(call)
    
    // Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to
    // the same host.
    if (!call.get().forWebSocket) {
      val existingCall = findExistingCallWithHost(call.host())
      if (existingCall != null) call.reuseCallsPerHostFrom(existingCall)
    }
  }
  promoteAndExecute()
}

在这段代码里面只讲call加入至对列,并没有发现发起请求的代码,继续往下看 promoteAndExecute 方法内的代码

/**
 * Promotes eligible calls from [readyAsyncCalls] to [runningAsyncCalls] and runs them on the
 * executor service. Must not be called with synchronization because executing calls can call
 * into user code.
 *
 * @return true if the dispatcher is currently running calls.
 */
private fun promoteAndExecute(): Boolean {
  assert(!Thread.holdsLock(this))
    //需要执行的请求
  val executableCalls = mutableListOf<AsyncCall>()
  val isRunning: Boolean
  synchronized(this) {
    val i = readyAsyncCalls.iterator()
    //遍历readyAsyncCalls对列
    while (i.hasNext()) {
      val asyncCall = i.next()
            //判断runningAsyncCalls的异步请求数
      if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity.
      if (asyncCall.callsPerHost().get() >= this.maxRequestsPerHost) continue // Host max capacity.
            //如果runningAsyncCalls数小于最大请求
      //把此请求从readyAsyncCalls移除并加入到runningAsyncCalls中
      //同时加入到executableCalls
      i.remove()
      asyncCall.callsPerHost().incrementAndGet()
      executableCalls.add(asyncCall)
      runningAsyncCalls.add(asyncCall)
    }
    isRunning = runningCallsCount() > 0
  }
    //调用executableCalls内所有asyncCall的executeOn方法
  for (i in 0 until executableCalls.size) {
    val asyncCall = executableCalls[i]
    asyncCall.executeOn(executorService)
  }

  return isRunning
}

在这里还是没有到发起请求,上一步请求加入至 readyAsyncCalls 对列,这一步从readyAsyncCalls 移至 runningAsyncCalls 然后执行 asyncCall.executeOn ,这里用到了 executorService 线程池。

@get:Synchronized
@get:JvmName("executorService") val executorService: ExecutorService
  get() {
    if (executorServiceOrNull == null) {
      executorServiceOrNull = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS,
          SynchronousQueue(), threadFactory("OkHttp Dispatcher", false))
    }
    return executorServiceOrNull!!
  }

继续往下看,回到AsyncCall

internal inner class AsyncCall(
  private val responseCallback: Callback
) : Runnable {
  /**
   * 省略相关代码
   */
  fun executeOn(executorService: ExecutorService) {
    assert(!Thread.holdsLock(client.dispatcher))
    var success = false
    try {
      //添加至线程池
      executorService.execute(this)
      success = true
    } catch (e: RejectedExecutionException) {
      val ioException = InterruptedIOException("executor rejected")
      ioException.initCause(e)
      transmitter.noMoreExchanges(ioException)
      //请求失败回调
      responseCallback.onFailure(this@RealCall, ioException)
    } finally {
      if (!success) {
        //添加至线程池失败,从调度器的对列中移除此次请求
        client.dispatcher.finished(this) // This call is no longer running!
      }
    }
  }

  override fun run() {
    threadName("OkHttp ${redactedUrl()}") {
      var signalledCallback = false
      transmitter.timeoutEnter()
      try {
        //获取请求结果
        val response = getResponseWithInterceptorChain()
        signalledCallback = true
        //请求成功回调
        responseCallback.onResponse(this@RealCall, response)
      } catch (e: IOException) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for ${toLoggableString()}", e)
        } else {
          //请求失败回调
          responseCallback.onFailure(this@RealCall, e)
        }
      } finally {
                    // 请求结束 从调度器的对列中移除此次请求
        client.dispatcher.finished(this)
      }
    }
  }
}

前面提到过AsyncCall实现了Runnable接口,这里在executeOn 方法内会将自己加入到调度器传过来的线程池中,执行run方法。这里的请求也和同步请求一样最终调用getResponseWithInterceptorChain

大致流程如下

OKHttp请求流程

拦截器链的调用

在OKHttp的网络请求过程主要依靠拦截器,使用责任链模式。接着上面的往下查看getResponseWithInterceptorChain 方法

@Throws(IOException::class)
fun getResponseWithInterceptorChain(): Response {
  // Build a full stack of interceptors.
  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)
    }
  }

getResponseWithInterceptorChain方法内会将自定义过滤器和系统的过滤器封装为一个RealInterceptorChain 过滤器链,然后调用proceed方法,在proceed方法内

@Throws(IOException::class)
fun proceed(request: Request, transmitter: Transmitter, exchange: Exchange?): Response {
  if (index >= interceptors.size) throw AssertionError()
//为下一个过滤器构建一个过滤器链 index + 1 下标加一
  val next = RealInterceptorChain(interceptors, transmitter, exchange,
      index + 1, request, call, connectTimeout, readTimeout, writeTimeout)
  val interceptor = interceptors[index]
//执行当前下标的过滤器
  @Suppress("USELESS_ELVIS")
  val response = interceptor.intercept(next) ?: throw NullPointerException(
      "interceptor $interceptor returned null")

  return response
}

在过滤器的intercept的方法里面

    @Override
   public Response intercept(Chain chain) throws IOException {
             //省略相关逻辑 基本过滤器都是这个格式 
          Request request = chain.request();
          //这里的chain的下标是下一个过滤器链的下标了 
                //调用proceed方法又会回到上代码 执行下一个过滤方法。
            Response response = chain.proceed(request);
            return response;
        }

这个实现过程就是使用了责任链模式,关于责任链模式不过多的说了。往下走逐个分析拦截器

RetryAndFollowUpInterceptor 重定向拦截器,

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  var request = chain.request()
  val realChain = chain as RealInterceptorChain
  val transmitter = realChain.transmitter()
  var followUpCount = 0
  var priorResponse: Response? = null
  //开启死循环
  while (true) {
    transmitter.prepareToConnect(request)

    if (transmitter.isCanceled) {
      throw IOException("Canceled")
    }

    var response: Response
    var success = false
    try {
      //从拦截器链获取请求结果
      response = realChain.proceed(request, transmitter, null)
      success = true
    }   catch (e: RouteException) {
        if (!recover(e.lastConnectException, transmitter, false, request)) {
          throw e.firstConnectException
        }
        continue
      } catch (e: IOException) {
        val requestSendStarted = e !is ConnectionShutdownException
        if (!recover(e, transmitter, requestSendStarted, request)) throw e
        continue
      } finally {
        // The network call threw an exception. Release any resources.
        if (!success) {
          transmitter.exchangeDoneDueToException()
        }
      }

    if (priorResponse != null) {
      response = response.newBuilder()
          .priorResponse(priorResponse.newBuilder()
              .body(null)
              .build())
          .build()
    }

    val exchange = response.exchange
    val route = exchange?.connection()?.route()
    //对请求结果进行处理 判断是否需要重定向或者重试
    //并且返回处理过的request
    val followUp = followUpRequest(response, route)

    if (followUp == null) {
      if (exchange != null && exchange.isDuplex) {
        transmitter.timeoutEarlyExit()
      }
      //返回结果 跳出循环
      return response
    }

    val followUpBody = followUp.body
    if (followUpBody != null && followUpBody.isOneShot()) {
      //返回结果 跳出循环
      return response
    }

    response.body?.closeQuietly()
    if (transmitter.hasExchange()) {
      exchange?.detachWithViolence()
    }

    if (++followUpCount > MAX_FOLLOW_UPS) {
      throw ProtocolException("Too many follow-up requests: $followUpCount")
    }
        //重新赋值request 开启下一次循环
    request = followUp
    priorResponse = response
  }
}

在这个拦截器中是一个死循环,从拦截器链中获取请求请求结果,通过方法followUpRequest对结果进行处理,判断是否需要重定向或者重试,如果判断请求成功的话跳出循环返回结果,否则的话继续下一次循环。

BridgeInterceptor 拦截器

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

  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {
    val userRequest = chain.request()
    val requestBuilder = userRequest.newBuilder()

    val body = userRequest.body
    /* 添加请求参数 开始 */
    if (body != null) {
      val contentType = body.contentType()
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString())
      }

      val contentLength = body.contentLength()
      if (contentLength != -1L) {
        requestBuilder.header("Content-Length", contentLength.toString())
        requestBuilder.removeHeader("Transfer-Encoding")
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked")
        requestBuilder.removeHeader("Content-Length")
      }
    }

    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", userRequest.url.toHostHeader())
    }

    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive")
    }

    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    var transparentGzip = false
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true
      requestBuilder.header("Accept-Encoding", "gzip")
    }

    val cookies = cookieJar.loadForRequest(userRequest.url)
    if (cookies.isNotEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies))
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", userAgent)
    }
     /* 添加请求参数 开始 */
    
    //从链内获取请求结果
    val networkResponse = chain.proceed(requestBuilder.build())

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

    val responseBuilder = networkResponse.newBuilder()
        .request(userRequest)
        //判断结果是否压缩
    if (transparentGzip &&
        "gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) &&
        networkResponse.promisesBody()) {
      val responseBody = networkResponse.body
      if (responseBody != null) {
        val gzipSource = GzipSource(responseBody.source())
        val strippedHeaders = networkResponse.headers.newBuilder()
            .removeAll("Content-Encoding")
            .removeAll("Content-Length")
            .build()
        responseBuilder.headers(strippedHeaders)
        val contentType = networkResponse.header("Content-Type")
        responseBuilder.body(RealResponseBody(contentType, -1L, gzipSource.buffer()))
      }
    }

    return responseBuilder.build()
  }

  /** Returns a 'Cookie' HTTP request header with all cookies, like `a=b; c=d`. */
  private fun cookieHeader(cookies: List<Cookie>): String = buildString {
    cookies.forEachIndexed { index, cookie ->
      if (index > 0) append("; ")
      append(cookie.name).append('=').append(cookie.value)
    }
  }
}

这个拦截器内代码比较简单,在请求前添加请求头等参数,在请求完之后进行数据压缩

CacheInterceptor 拦截器

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  //从缓存中获取缓存的Response对象
  val cacheCandidate = cache?.get(chain.request())

  val now = System.currentTimeMillis()
    //通过缓存的response对象和request来创建一个缓存策略对象
  val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()
  //从缓存策略对象中拿出networkRequest和cacheResponse
  // networkRequest为空说明不需要请求网络,cacheResponse为空说明没有缓存可用
  val networkRequest = strategy.networkRequest
  val cacheResponse = strategy.cacheResponse

  cache?.trackResponse(strategy)
    //获取的缓存不为空,但是缓存策略中获取的为空,说明此缓存不适用,
  if (cacheCandidate != null && cacheResponse == null) {
    // The cache candidate wasn't applicable. Close it.
    cacheCandidate.body?.closeQuietly()
  }

    //networkRequest和cacheResponse都为空 
  //直接return返回code为HTTP_GATEWAY_TIMEOUT 504的response
  if (networkRequest == null && cacheResponse == null) {
    return Response.Builder()
        .request(chain.request())
        .protocol(Protocol.HTTP_1_1)
        .code(HTTP_GATEWAY_TIMEOUT)
        .message("Unsatisfiable Request (only-if-cached)")
        .body(EMPTY_RESPONSE)
        .sentRequestAtMillis(-1L)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build()
  }

  //networkRequest为空 cacheResponse不为空加载缓存
  if (networkRequest == null) {
    return cacheResponse!!.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .build()
  }
    //networkRequest不为空 cacheResponse为空加载网络请求
  var networkResponse: Response? = null
  try {
    //网络请求
    networkResponse = chain.proceed(networkRequest)
  } finally {
    // If we're crashing on I/O or otherwise, don't leak the cache body.
    if (networkResponse == null && cacheCandidate != null) {
      cacheCandidate.body?.closeQuietly()
    }
  }

  // 原有缓存
  if (cacheResponse != null) {
    if (networkResponse?.code == HTTP_NOT_MODIFIED) {
      //合并操作
      val response = cacheResponse.newBuilder()
          .headers(combine(cacheResponse.headers, networkResponse.headers))
          .sentRequestAtMillis(networkResponse.sentRequestAtMillis)
          .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis)
          .cacheResponse(stripBody(cacheResponse))
          .networkResponse(stripBody(networkResponse))
          .build()

      networkResponse.body!!.close()

      //更新缓存
      cache!!.trackConditionalCacheHit()
      cache.update(cacheResponse, response)
      return response
    } else {
      cacheResponse.body?.closeQuietly()
    }
  }

  val response = networkResponse!!.newBuilder()
      .cacheResponse(stripBody(cacheResponse))
      .networkResponse(stripBody(networkResponse))
      .build()
//写入缓存
  if (cache != null) {
    if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {
      // Offer this request to the cache.
      val cacheRequest = cache.put(response)
      return cacheWritingResponse(cacheRequest, response)
    }

    if (HttpMethod.invalidatesCache(networkRequest.method)) {
      try {
        cache.remove(networkRequest)
      } catch (_: IOException) {
        // The cache cannot be written.
      }
    }
  }

  return response
}

在缓存拦截器中,首先是从缓存中获取cache获取缓存,

val cacheCandidate = cache?.get(chain.request())
//cache中的get方法
internal fun get(request: Request): Response? {
  val key = key(request.url)
  val snapshot: DiskLruCache.Snapshot = try {
    cache[key] ?: return null
  } catch (_: IOException) {
    return null // Give up because the cache cannot be read.
  }
    //省略相关代码
  return response
}

//key方法
@JvmStatic
fun key(url: HttpUrl): String = url.toString().encodeUtf8().md5().hex()

可以看到缓存是使用了DiskLruCache,缓存的key是使用了请求的url生成的md5。

获取缓存之后,通过 request 和缓存 response 来创建一个缓存策略对象,关于缓存策略的实现不在这里分析。只关注请求的大致流程。接着调用 compute 方法判断本次请求是否有可用的缓存还是发起网络请求。拿到 strategy 内的 networkRequestcacheResponse

  • networkRequest 为空代表不需要网络请求,cacheResponse 为空代表无可用缓存。
  • networkRequestcacheResponse 都为空返回504
  • networkRequest 为空, cacheResponse不为空,返回缓存。
  • networkRequest 不为空,发起网络请求。

获取网络请求后,会更新缓存或是添加至缓存。这里只简单分析了流程,并没有分析缓存策略,在后面会单独写文章来分析缓存策略。

ConnectInterceptor拦截器

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  val realChain = chain as RealInterceptorChain
  val request = realChain.request()
  val transmitter = realChain.transmitter()

  // We need the network to satisfy this request. Possibly for validating a conditional GET.
  val doExtensiveHealthChecks = request.method != "GET"
  val exchange = transmitter.newExchange(chain, doExtensiveHealthChecks)

  return realChain.proceed(request, transmitter, exchange)
}

这个拦截器代码很简单,只有一行重要代码 transmitter.newExchange ,主要任务是在链接池中开启一个新的链接,并建立与服务器的连接。关于连接池的代码在这里不过多分析,后面也会单独写文章分析。

CallServerInterceptor请求拦截器

这个拦截器才是最终负责向服务器写入请求数据和读取响应结果。

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  val realChain = chain as RealInterceptorChain
  val exchange = realChain.exchange()
  val request = realChain.request()
  val requestBody = request.body
  val sentRequestMillis = System.currentTimeMillis()
    //向服务器写入请求头
  exchange.writeRequestHeaders(request)

  var responseHeadersStarted = false
  var responseBuilder: Response.Builder? = null
  //判断是否有请求body
  if (HttpMethod.permitsRequestBody(request.method) && requestBody != null) {
    //头部添加了"100-continue" 只有拿到服务的结果再继续
    if ("100-continue".equals(request.header("Expect"), ignoreCase = true)) {
      exchange.flushRequest()
      responseHeadersStarted = true
      //读取请求头
      exchange.responseHeadersStart()
      responseBuilder = exchange.readResponseHeaders(true)
    }
    //向服务器写入请求body
    if (responseBuilder == null) {
      if (requestBody.isDuplex()) {
        exchange.flushRequest()
        val bufferedRequestBody = exchange.createRequestBody(request, true).buffer()
        requestBody.writeTo(bufferedRequestBody)
      } else {
        val bufferedRequestBody = exchange.createRequestBody(request, false).buffer()
        requestBody.writeTo(bufferedRequestBody)
        bufferedRequestBody.close()
      }
    } else {
     //没有请求body
      exchange.noRequestBody()
      if (!exchange.connection()!!.isMultiplexed) {
        exchange.noNewExchangesOnConnection()
      }
    }
  } else {
    //没有请求body
    exchange.noRequestBody()
  }

  if (requestBody == null || !requestBody.isDuplex()) {
    exchange.finishRequest()
  }
  //如果之前没有读取过请求头 开始读取请求头
  if (!responseHeadersStarted) {
    exchange.responseHeadersStart()
  }
  if (responseBuilder == null) {
    responseBuilder = exchange.readResponseHeaders(false)!!
  }
  //在这里开始构建response
  var response = responseBuilder
      .request(request)
      .handshake(exchange.connection()!!.handshake())
      .sentRequestAtMillis(sentRequestMillis)
      .receivedResponseAtMillis(System.currentTimeMillis())
      .build()
  var code = response.code
  if (code == 100) {
    // server sent a 100-continue even though we did not request one.
    // try again to read the actual response
    response = exchange.readResponseHeaders(false)!!
        .request(request)
        .handshake(exchange.connection()!!.handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build()
    code = response.code
  }

  exchange.responseHeadersEnd(response)
    //状态码等于101 或者当前连接是forWebSocket的时候 返回一个空的body
  response = if (forWebSocket && code == 101) {
    response.newBuilder()
        .body(EMPTY_RESPONSE)
        .build()
  } else {
    //读取服务器返回的body
    response.newBuilder()
        .body(exchange.openResponseBody(response))
        .build()
  }
  if ("close".equals(response.request.header("Connection"), ignoreCase = true) ||
      "close".equals(response.header("Connection"), ignoreCase = true)) {
    exchange.noNewExchangesOnConnection()
  }
  if ((code == 204 || code == 205) && response.body?.contentLength() ?: -1L > 0L) {
    throw ProtocolException(
        "HTTP $code had non-zero Content-Length: ${response.body?.contentLength()}")
  }
  return response
}

这个拦截器主要完成了和服务器的交互,这里也只简单分析,深层相关在这里不做多分析。

根据上面的分析,拦截器部分基本分析完了。流程如下

OKHttp拦截器执行过程

关于缓存策略,连接池等其他部分篇幅有限,以后逐个分析。

个人学习笔记,如有不对感谢大佬们指出。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容