okhttp——BridgeInterceptor

簡(jiǎn)介

okhttp的網(wǎng)絡(luò)請(qǐng)求采用interceptors鏈的模式。每一級(jí)interceptor只處理自己的工作,然后將剩余的工作,交給下一級(jí)interceptor。本文將主要閱讀okhttp中的BridgeInterceptor,了解它的作用和工作原理。

BridgeInterceptor

BridgeInterceptor從名字上很難看出它的含義。其實(shí),它是一個(gè)處理請(qǐng)求返回的攔截器,它會(huì)對(duì)請(qǐng)求的Header進(jìn)行一些處理,然后將工作交到下一級(jí)Interceptor,下一級(jí)完成后,再對(duì)返回進(jìn)行處理。

/**
 * Bridges from application code to network code. First it builds a network request from a user
 * request. Then it proceeds to call the network. Finally it builds a user response from the network
 * response.
 */
class BridgeInterceptor(private val cookieJar: CookieJar) : Interceptor {
  ...
}

從注釋中我們也可以看出,BridgeInterceptor的實(shí)現(xiàn)主要分兩部分:請(qǐng)求的處理返回的處理。

Request

  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", hostHeader(userRequest.url(), false))
    }

    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)
    }
    ...
}

這一部分,主要是對(duì)Request的Headers進(jìn)行處理。如果調(diào)用者,有自行設(shè)置相關(guān)的Header,則直接從userRequestbody中獲取,然后設(shè)置到requestBuilder中。這里有幾處參數(shù)的處理值得注意。

contentLength

      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")
      }

獲取body的內(nèi)容長(zhǎng)度。如果內(nèi)容長(zhǎng)度不為-1,則設(shè)置長(zhǎng)度,并去除"Transfer-Encoding"。如果內(nèi)容長(zhǎng)度為-1,則是chunked模式,去掉"Content-Length"。

gzip

    // 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")
    }

如果用戶沒有指定Accept-Encoding,且請(qǐng)求沒有帶Range字段時(shí),可以自動(dòng)轉(zhuǎn)換為gzip。

Response

完成了Request后,我們會(huì)委托給下層進(jìn)行實(shí)現(xiàn),然后將networkResponse返回給我們。Response中,主要是需要對(duì)transparentGzip進(jìn)行判斷。如果是gzip模式,則需要進(jìn)行一些處理。

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

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

    val responseBuilder = networkResponse.newBuilder()
        .request(userRequest)

    if (transparentGzip &&
        "gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) &&
        HttpHeaders.hasBody(networkResponse)) {
      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()
  }

如果Response是gzip模式且transparentGzip為true且HttpHeaders.hasBody為true時(shí),會(huì)去掉Headers中的"Content-Encoding"和"Content-Length"。

這個(gè)地方值得深究一下。

transparentGzip為true的條件是:

    var transparentGzip = false
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true
      requestBuilder.header("Accept-Encoding", "gzip")
    }
  /** Returns true if the response must have a (possibly 0-length) body. See RFC 7231. */
  public static boolean hasBody(Response response) {
    // HEAD requests never yield a body regardless of the response headers.
    if (response.request().method().equals("HEAD")) {
      return false;
    }

    int responseCode = response.code();
    if ((responseCode < HTTP_CONTINUE || responseCode >= 200)
        && responseCode != HTTP_NO_CONTENT
        && responseCode != HTTP_NOT_MODIFIED) {
      return true;
    }

    // If the Content-Length or Transfer-Encoding headers disagree with the response code, the
    // response is malformed. For best compatibility, we honor the headers.
    if (contentLength(response) != -1
        || "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) {
      return true;
    }

    return false;
  }

所以,okhttp會(huì)去掉Headers中的"Content-Encoding"和"Content-Length"的條件是:

  • 用戶未設(shè)置Request的"Accept-Encoding"
  • 用戶未設(shè)置Request的"Range"
  • Response中"Content-Encoding"為gzip

當(dāng)用戶未設(shè)置Accep-Encoding時(shí),用戶期望的Content-Length是返回的內(nèi)容長(zhǎng)度。但由于okhttp在用戶未設(shè)置Accep-Encoding時(shí),會(huì)進(jìn)行g(shù)zip的轉(zhuǎn)換。

當(dāng)HTTP使用gzip方式時(shí),Content-Length的返回是根據(jù)gzip壓縮后的長(zhǎng)度進(jìn)行返回的。此時(shí)Content-Length的值與用戶所期望的不符的。因?yàn)橛脩舨]有主動(dòng)使用gzip模式。

所以,此時(shí)okhttp選擇將Content-Length remove掉,以免讓調(diào)用者產(chǎn)生誤解。

不得不說(shuō)okhttp在此處的處理略顯粗暴,但也不是完全不能理解。
Issue中也有相關(guān)的討論

issue

總結(jié)

okhttpBridgeInterceptor處理了HTTP的請(qǐng)求中對(duì)于請(qǐng)求Header和返回Header。對(duì)于HTTP模式的各種匹配做了相應(yīng)的適配和容錯(cuò)。

如有問(wèn)題,歡迎指正。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容