Python 请求从 POST 中删除 Content-Length 标头 [英] Python requests remove the Content-Length header from POST
问题描述
我正在使用 python requests 模块对网站进行一些测试.
I'm using the python requests module to do some testing against a site.
requests 模块允许您通过传入一个键设置为 None 的字典来删除某些标头.例如
The requests module allows you to remove certain headers by passing in a dictionary with the keys set to None. For example
headers = {u'User-Agent': None}
将确保没有用户代理随请求一起发送.
will ensure that no user agent is sent with the request.
但是,似乎当我发布数据时,即使我指定了 None 或不正确的值,请求也会为我计算正确的 Content-Length.例如.
However, it seems that when I post data, requests will calculate the correct Content-Length for me even if I specify None, or an incorrect value. Eg.
headers = {u'Content-Length': u'999'}
headers = {u'Content-Length': None}
我检查了请求中使用的标头的响应 (response.request.headers),我可以看到 Content-Length 已使用正确的值重新添加.到目前为止,我看不到任何方法可以禁用此行为
I check the response for the headers used in the request (response.request.headers) and I can see the Content-Length has been re-added with the correct value. So Far I cannot see any way to disable this behaviour
CaseInsensitiveDict({'Content-Length': '39', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'python-requests/2.2.1 CPython/2.7.6 Linux/3.13.0-36-generic'})
我真的很想继续使用请求模块来做到这一点.这可能吗?
I'd REALLY like to remain with the requests module to do this. Is this possible?
推荐答案
你必须手动准备请求,然后移除生成的 content-length 头:
You'll have to prepare the request manually, then remove the generated content-length header:
from requests import Request, Session
s = Session()
req = Request('POST', url, data=data)
prepped = req.prepare()
del prepped.headers['content-length']
response = s.send(prepped)
请注意,大多数合规的 HTTP 服务器可能会忽略您的帖子正文!
Do note that most compliant HTTP servers may then ignore your post body!
如果您打算使用分块传输编码(您不必发送内容长度),然后对 data
参数使用迭代器.请参阅分块编码请求 在文档中.在这种情况下不会设置 Content-Length
标头.
If you meant to use chunked transfer encoding (where you don't have to send a content length), then use a iterator for the data
parameter. See Chunked-Encoded Requests in the documentation. No Content-Length
header will be set in that case.
这篇关于Python 请求从 POST 中删除 Content-Length 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!