使用Python计算内容长度

时间:2012-03-13 22:09:43

标签: python http http-headers http-request python-requests

我正在尝试发帖,但每次我这样做,我都会收到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中)

2 个答案:

答案 0 :(得分:1)

只要发送POST标头并将其设置为Content-Length,就向空主体发送0请求是完全合法的。 请求通常会计算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": ""
}

答案 1 :(得分:0)

在没有post参数的情况下使用data方法看起来很奇怪(但是将数据放在网址中)。

查看official requests documentation

中的示例
>>> 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": ""
}