接收端依優先順序判斷訊息長度:
chunked) → **優先使用 TE 解碼機制確定長度**,**必須忽略 Content-Length** (若同時存在)。| 場景 | Content-Length | Transfer-Encoding | 長度確定方式 |
|---|---|---|---|
| 固定長度、無壓縮、HTTP/1.1 Keep-Alive | **必須有**,值 = 實體長度 = 傳輸長度 | 無 | Content-Length |
| gzip/deflate 壓縮 | **必須有**,值 = **壓縮後**長度 | 無 (Content-Encoding: gzip) | Content-Length |
| Chunked 編碼 | **禁止出現** | chunked | Chunk 解析 (0 長度 chunk 結束) |
| HTTP/1.0 或 Connection: close | 可有可無 | 無 | 連線關閉 |
| 1xx/204/304/HEAD | 忽略 | 忽略 | 無實體 |
**錯誤**。若啟用 Content-Encoding: gzip,Content-Length 必須是**壓縮後**的位元組數。接收端先按 Content-Length 讀取完整壓縮資料流,再解壓縮。
**違反協議**。RFC 7230 明確要求:If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. 但發送端**不應同時發送**,中介設備 (Proxy/WAF) 可能直接拒絕或行為未定義。
**不完全**。Chunked 亦用於**邊生成邊傳輸** (流式響應)、**避免緩衝大量資料**、或**傳輸編碼層面的分塊**。即使知道總長度,也可選用 Chunked。
| 版本 | Keep-Alive | Content-Length 必要性 | Chunked 支援 |
|---|---|---|---|
| HTTP/1.0 | 預設關閉 (需 Connection: keep-alive) | 可有可無 (無則靠關閉連線) | 不支援 (伺服器不解析) |
| HTTP/1.1 | 預設開啟 | **Keep-Alive 時必須有 CL 或 TE:chunked** | **必須支援** |
curl -v https://example.com/ 2>&1 | grep -i -E 'content-length|transfer-encoding|content-encoding'
import requests
r = requests.get('https://httpbin.org/stream/5', stream=True)
print(r.headers.get('Transfer-Encoding')) # chunked
print(r.headers.get('Content-Length')) # None
# iter_content() 自動處理 chunk 解碼
# 靜態檔案自動發送 Content-Length
# 動態代理 (proxy_pass) 預設啟用 chunked (HTTP/1.1 後端)
# 強制發送 Content-Length (緩衝完整回應後)
proxy_buffering on;
proxy_buffers 8 16k;
# 禁用 chunked (HTTP/1.0 後端)
proxy_http_version 1.0;
proxy_set_header Connection "";