[英]Calculating Content-Length with Python
我正在尝试发帖,但是每次我发帖时,都会收到 411 响应错误。 我正在使用 python 中的请求库。
In [1]: r.post(url)
Out[1]: <Response [411]>
然后我指定了内容长度h = {'content-length': '0'}
并重试。
In [2]: r.post(url,h)
Out[2]: <Response [200]>
太好了,我成功了,但是没有发布任何信息。
我想我需要计算内容长度,这是有道理的,因为它可能会“切断”帖子。
所以我的问题是,给定 url www.example.com/import.php?key=value&key=value
我如何计算content-length
? (如果可能,在 python 中)
只要Content-Length
标头被发送并设置为0
发送带有空主体的POST
请求就完全合法。 请求通常计算Content-Length
标头的值。 您观察到的行为可能是由于问题223 - 缺少Content-Length。 虽然错误没有关闭,但看起来修复了问题:
C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.__version__
'0.11.1'
>>> r = requests.post('http://httpbin.org/post?key1=valueA&key2=valueB')
>>> print r.content
{
"origin": "77.255.249.138",
"files": {},
"form": {},
"url": "http://httpbin.org/post?key1=valueA&key2=valueB",
"args": {
"key2": "valueB",
"key1": "valueA"
},
"headers": {
"Content-Length": "0",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.11.1",
"Host": "httpbin.org",
"Content-Type": ""
},
"json": null,
"data": ""
}
如果您从 postman 中找到相同的 API,它将起作用。 原因是因为 postman 在调用 API 时自动在 header 中包含内容长度。 如果您尝试取消选中 postman 中的内容长度,则它不起作用。
这个问题是间歇性发生的。 如果您在没有内容长度的情况下(有时)和 400 或其他任何一个在 body 不存在时抛出的东西,您仍然会得到 200 响应。
所以这里的技巧是,您尝试访问的 API 主机有时会尝试自行计算内容长度,有时当流量很大时,它实际上被配置为不利用其功率/时间来计算内容长度,因此当没有给出 content-length 时,它认为没有正文。 所以如果你给 content-length: 0 那么它实际上每次都会计算 content-length 因为在数据传输过程中它可以压缩和解压缩。
还
while(times--):
requests.post(url,headers)
上面没有工作,但下面的工作。
while(times--):
requests.post(url,headers)
time.sleep(2.5)
你使用没有data
参数的post
方法(但是将数据放在url中)看起来很奇怪。
查看官方请求文档中的示例:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
"origin": "179.13.100.4",
"files": {},
"form": {
"key2": "value2",
"key1": "value1"
},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "23",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Accept": "*/*",
"User-Agent": "python-requests/0.8.0",
"Host": "127.0.0.1:7077",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": ""
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.