如何在 python 中强制 http.client 发送分块编码的 HTTP 正文?
我想发送分块的 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请求的主体没有分块传输。
如何通过Python中的http.client lib传输分块主体?
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)
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.
How to transfer chunked body by http.client lib in python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,我明白了。
首先,编写我自己的分块编码函数。
然后使用 putrequest()、putheader()、endheaders() 和 send() 而不是 request()
OK, I get it.
First, write my own chunked encode function.
Then use putrequest(), putheader(), endheaders() and send() instead of request()
我建议,如果您已经知道数据的大小(如答案中所示),您只需设置
Content-Length
并将其全部发送回一次,这就是您通过一次调用conn.send
所做的事情。当您不知道数据有多大(例如动态生成的内容)时,分块传输编码最有用。我修改了你的代码来说明:
I'd suggest that if you already know the size of your data like in the answer given you could just set the
Content-Length
and send it all back in one hit, which is kind of what you're doing with the single call toconn.send
anyway.Chunked transfer encoding is most useful when you don't know how big the data is e.g. dynamically generated content. I've modified your code to illustrate: