如何强制http.client在python中发送chunked-encoding HTTP正文? [英] How to force http.client to send chunked-encoding HTTP body in python?
本文介绍了如何强制http.client在python中发送chunked-encoding HTTP正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想发送分块的HTTP主体来测试我自己的HTTP服务器。
所以我写了这个python代码:
I want to send chunked HTTP body to test my own HTTP server. So I wrote this python code:
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 chunked,
但是我使用Wireshark捕获网络包,HTTP请求的主体不会被转移分块。
I expect the HTTP request's body is transferrd chunked, but I capture the network package with Wireshark, the HTTP request's body is not transferred chunked.
如何通过python中的http.client lib传输chunked body?
推荐答案
好的,我明白了。
首先,写一下我自己的分块编码功能。
First, write my own chunked encode function.
然后使用putrequest(),putheader(),endheaders()和send()而不是request()
Then use putrequest(), putheader(), endheaders() and send() instead of 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()
这篇关于如何强制http.client在python中发送chunked-encoding HTTP正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文