簡體   English   中英

為什么 204 沒有被 OkHttp 緩存?

[英]Why 204 are not cached by OkHttp?

查看CacheInterceptor中的代碼,我看到代碼 204 的響應沒有被緩存。 但我相信 204 是可緩存的,正如這里所討論的

我們使用204作為對 GET 的響應並不表示空響應,而且最近才注意到那些沒有被緩存。

當沒有內容時返回204 - “服務器成功處理了請求並且沒有返回任何內容”。

因此,如果使用規范代碼,則沒有要緩存的數據。 如果您返回的內容/數據超過200則更合適。

原因有很多。

為什么實現的行為是這樣的?

從技術上講,跳過 204 是因為如果promisesBody返回trueintercept方法只會緩存響應

      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完全相同,並且有效響應不應包含該內容。

tl;博士

這是一個錯誤,遇到這種情況的人都沒有報告過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM