6

我正在尝试发帖,但是每次我发帖时,都会收到 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]>

太好了,我成功了,但是没有发布任何信息。

我想我需要计算内容长度,这是有道理的,因为它可能会“切断”帖子。

所以我的问题是,给定一个网址www.example.com/import.php?key=value&key=value,我该如何计算content-length?(如果可能,在 python 中)

4

2 回答 2

1

使用post不带data参数的方法(但将数据放在 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": ""
}
于 2012-03-20T13:28:09.097 回答
1

POST只要Content-Length标头被发送并设置为 ,发送带有空正文的请求是完全合法的0请求通常计算Content-Length标头的值。您观察到的行为可能是由于问题223 - Content-Length is missing。尽管该错误尚未关闭,但问题似乎已解决:

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": ""
}
于 2012-04-17T20:03:28.717 回答