簡(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,則直接從userRequest的body中獲取从铲,然后設(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")
}
如果用戶沒(méi)有指定Accept-Encoding窃蹋,且請(qǐng)求沒(méi)有帶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)橛脩舨](méi)有主動(dòng)使用gzip模式懂版。
所以鹃栽,此時(shí)okhttp選擇將Content-Length remove掉,以免讓調(diào)用者產(chǎn)生誤解躯畴。
不得不說(shuō)okhttp在此處的處理略顯粗暴民鼓,但也不是完全不能理解。
Issue中也有相關(guān)的討論
總結(jié)
okhttp的BridgeInterceptor處理了HTTP的請(qǐng)求中對(duì)于請(qǐng)求Header和返回Header蓬抄。對(duì)于HTTP模式的各種匹配做了相應(yīng)的適配和容錯(cuò)丰嘉。
如有問(wèn)題,歡迎指正嚷缭。