我正在 Python3 中實作一個簡單的反向代理,我需要發送一個帶有transfer-encoding chunked模式的回應。
我從這篇
但是如果我改用這個長度:
# writing the same 5 chunks of 9 characters
for i in range(5):
text = str(i 1) * 9 # concatenate 9 chars
chunk = '{0:d}\r\n'.format(len(text)) text '\r\n'
self.wfile.write(chunk.encode(encoding='utf-8'))
# writing close sequence
close_chunk = '0\r\n\r\n'
self.wfile.write(close_chunk.encode(encoding='utf-8'))
通信正確結束(6 毫秒后,所有 5 個塊都被正確解釋)

部分版本資訊:
HTTP Client: Postman 8.10
(venv) manuel@MBP ReverseProxy % python -V
Python 3.9.2
(venv) manuel@MBP ReverseProxy % pip freeze
certifi==2021.10.8
charset-normalizer==2.0.6
idna==3.2
requests==2.26.0
urllib3==1.26.7
提前感謝您的任何提示!
uj5u.com熱心網友回復:
我發布了解決方案(感謝來自 bugs.python.org 的 Martin Panter),以防其他人將來遇到同樣的問題。
該行為是由塊大小部分引起的,它必須是十六進制格式,而不是十進制。
不幸的是,Mozilla檔案中沒有指定格式,示例中僅使用長度 < 10。這里有一個正式定義
總之,作業版本如下(使用{0:x}代替{0:d})
# writing the same 5 chunks of 9 characters
for i in range(5):
text = str(i 1) * 9 # concatenate 9 chars
chunk = '{0:x}\r\n'.format(len(text)) text '\r\n'
self.wfile.write(chunk.encode(encoding='utf-8'))
# writing close sequence
close_chunk = '0\r\n\r\n'
self.wfile.write(close_chunk.encode(encoding='utf-8'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330780.html
標籤:Python http http服务器 分块编码 分块
下一篇:網路for回圈異步
