Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

HTTP 協議深度解析:Content-Length、Transfer-Encoding 與 Chunked 傳輸機制

編輯:關於伺服器

在 HTTP 協議中,Content-Length 與 Transfer-Encoding 是決定訊息體長度與傳輸方式的兩大核心機制。理解它們的優先級、互斥關係與在 Keep-Alive/短連接下的行為差異,對排查傳輸截斷、超時、協議解析錯誤至關重要。

核心概念區分

概念定義典型值
Entity Length實體內容原始長度(壓縮前)100 KB
Transfer Length網絡傳輸實際字節數(壓縮後、Chunked 編碼後)30 KB (gzip) / 不定
Content-Length標示 Transfer Length(非 Entity Length)Content-Length: 30720
Transfer-Encoding標示傳輸編碼方式,如 chunked、gzipTransfer-Encoding: chunked

HTTP/1.1 訊息長度判定規則 (RFC 7230 Section 3.3)

接收端按以下優先級判斷訊息體結束:

  1. 特定狀態碼/方法:1xx、204、304 響應及 HEAD 請求 無訊息體,直接忽略長度字段。
  2. Transfer-Encoding: chunked:最高優先級。以 0\r\n\r\n 結束標記判定結束,**不可同時存在 Content-Length**(若共存需移除 CL)。
  3. Content-Length:若無 Transfer-Encoding,以 CL 值為準。值必須與實際傳輸字節數**完全一致**;過短導致截斷,過長導致讀取超時。
  4. 多媒體類型 multipart/byteranges:以邊界分隔符判定。
  5. 關閉連接:HTTP/1.0 或無 Keep-Alive 時,服務端關閉連接標示結束(**請求端不可用此方式**,否則服務端無法響應)。

Content-Length 與 Transfer-Encoding 互斥鐵律

若存在 Transfer-Encoding (尤其是 chunked),則禁止發送 Content-Length。 否則接收端行為未定義(大多數實現會忽略 CL 或報協議錯誤)。

常見錯誤場景:後端框架同時設置 Content-Length 與 Transfer-Encoding: chunked,導致 Nginx/客戶端解析異常。

Chunked 傳輸編碼詳解

格式:十六進制長度\r\n數據\r\n ... 0\r\n\r\n

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/plain

7\r\n
Mozilla\r\n
9\r\n
Developer\r\n
7\r\n
Network\r\n
0\r\n
\r\n

優勢:動態生成內容時無需預知總長度;支援邊生成邊傳輸(流式響應);配合 Trailer 頭傳輸元數據。

Keep-Alive 與短連接下的長度判定差異

連接模式HTTP/1.0HTTP/1.1 (Keep-Alive 默認開啟)
Content-Length可選(無則靠關閉連接判定)**必須**與 chunked 二選一
Transfer-Encoding: chunked不支援**必須**支援,作為無 CL 時的標準方案
無長度指示靠連接關閉判定協議錯誤(除非關閉連接)

實戰排查清單

  • 響應截斷:檢查 Content-Length 是否小於實際發送字節數(如 gzip 壓縮後未更新 CL)。
  • 客戶端等待超時:CL 大於實際字節數,或缺少 CL/Chunked 且連接未關閉。
  • 協議解析錯誤:同時存在 CL 和 Transfer-Encoding: chunked。
  • 壓縮傳輸:啟用 gzip/br 時,**必須移除原始 Content-Length**,由編碼層自動添加 Chunked 或重新計算 CL(僅當全量緩衝後壓縮)。
  • 範圍請求:206 Partial Content 必須包含準確 Content-Range 與 Content-Length(分片長度)。

總結

Content-Length 表示傳輸長度,而非實體長度。 HTTP/1.1 長連接下,傳輸長度指示器**非 CL 即 Chunked**,二者互斥。正確處理壓縮、流式響應、代理轉發時的長度字段重寫,是高效能 HTTP 服務與中間件開發的基本功。

Copyright © Windows教程網 All Rights Reserved