[英]Why 204 are not cached by OkHttp?
查看CacheInterceptor
中的代碼,我看到代碼 204 的響應沒有被緩存。 但我相信 204 是可緩存的,正如這里所討論的
我們使用204
作為對 GET 的響應並不表示空響應,而且最近才注意到那些沒有被緩存。
當沒有內容時返回204 - “服務器成功處理了請求並且沒有返回任何內容”。
因此,如果使用規范代碼,則沒有要緩存的數據。 如果您返回的內容/數據超過200則更合適。
原因有很多。
從技術上講,跳過 204 是因為如果promisesBody
返回true
則intercept
方法只會緩存響應:
if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
如您所料, promisesBody
為 204 個響應返回false
,除非它們具有Content-length
標頭或chunked
傳輸編碼:
/**
* Returns true if the response headers and status indicate that this response has a (possibly
* 0-length) body. See RFC 7231.
*/
...
val responseCode = 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 (headersContentLength() != -1L ||
"chunked".equals(header("Transfer-Encoding"), ignoreCase = true)) {
return true
}
return false
為了證明這一決定的合理性,OkHttp 緩存的一般用例可能是為了節省重新發送大型有效負載,而不是將往返次數保持在絕對最小值。 此外, 204 作為對GET
的響應是有效的,但更常用POST
的響應; 設計可能反映了這種啟發式的知識。
查看相關問題,有一個與更改某些狀態代碼的默認行為有關: OkHttp 默認緩存狀態代碼已過期:
該規范希望這些:200,203,204,206,300,301,404,405,410,414,和501
這導致了一個測試:
assertCached(true, 204);
HTTP/1.1 204 OK
...
Content-Length: 0
與它自己的檢測所需的不必要的Content-Length
完全相同,並且有效響應不應包含該內容。
這是一個錯誤,遇到這種情況的人都沒有報告過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.