我想发送分块的 HTTP 正文来测试我自己的 HTTP 服务器。 所以我写了这段 python 代码:
import http.client
body = 'Hello World!' * 80
conn = http.client.HTTPConnection("some.domain.com")
url = "/some_path?arg=true_arg"
conn.request("POST", url, body, {"Transfer-Encoding":"chunked"})
resp = conn.getresponse()
print(resp.status, resp.reason)
我希望 HTTP 请求的主体是 transferrd 分块的, 但是我用Wireshark抓包,HTTP请求的body没有分块传输。
如何在python中通过http.client lib传输分块的body?
最佳答案
好的,我明白了。
首先,编写我自己的分块编码函数。
然后使用 putrequest()、putheader()、endheaders() 和 send() 而不是 request()
import http.client
def chunk_data(data, chunk_size):
dl = len(data)
ret = ""
for i in range(dl // chunk_size):
ret += "%s\r\n" % (hex(chunk_size)[2:])
ret += "%s\r\n\r\n" % (data[i * chunk_size : (i + 1) * chunk_size])
if len(data) % chunk_size != 0:
ret += "%s\r\n" % (hex(len(data) % chunk_size)[2:])
ret += "%s\r\n" % (data[-(len(data) % chunk_size):])
ret += "0\r\n\r\n"
return ret
conn = http.client.HTTPConnection(host)
url = "/some_path"
conn.putrequest('POST', url)
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
conn.send(chunk_data(body, size_per_chunk).encode('utf-8'))
resp = conn.getresponse()
print(resp.status, resp.reason)
conn.close()
关于python - 如何强制 http.client 在 python 中发送分块编码的 HTTP 正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237961/