Python请求从POST中删除Content-Length标头 [英] Python requests remove the Content-Length header from POST
问题描述
我正在使用python请求模块对网站进行一些测试。
I'm using the python requests module to do some testing against a site.
请求模块允许您通过传入字典来删除某些标题。键设置为无。例如
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.
然而,似乎当我发布数据,请求将为我计算正确的Content-Length,即使我指定None或不正确的值。例如。
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}
我检查请求中使用的标头的响应(响应。 request.headers)我可以看到Content-Length已经重新添加了正确的值。到目前为止我看不到任何方法来禁用此行为
I check the response for the headers used in the request (response.request.headers) and I can see the 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?
推荐答案
你必须手动准备请求,然后删除生成的内容长度标题:
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
参数。请参阅 Chunked-Encoded Requests 在文档中。在这种情况下,将设置 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屋!