用 Python 计算内容长度

tsh*_*uck 6 python http http-headers http-request python-requests

我正在尝试发帖,但是每次我发帖时,都会收到 411 响应错误。我在 python 中使用请求库。

In [1]: r.post(url)
Out[1]: <Response [411]>
Run Code Online (Sandbox Code Playgroud)

然后我指定了内容长度h = {'content-length' : '0'}并重试。

In [2]: r.post(url,h)
Out[2]: <Response [200]>
Run Code Online (Sandbox Code Playgroud)

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

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

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

Leo*_*kov 1

post您使用没有的方法看起来很奇怪data argument (but put data in 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": ""
}
Run Code Online (Sandbox Code Playgroud)