【问题标题】:Calculating Content-Length with Python用 Python 计算内容长度
【发布时间】:2012-03-13 22:09:42
【问题描述】:

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

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&amp;key=value 我如何计算 content-length? (如果可能,在 python 中)

【问题讨论】:

  • 如果你只使用urllib,它是否有效? (我很惊讶request 不会自动填写 Content-Length 标头,因为它是基于 httplib 的。)
  • 请添加有关您正在使用的请求版本的信息。还请包括导致 411 响应状态代码的测试用例。

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


【解决方案1】:

您使用没有data 参数的post 方法看起来很奇怪(但将数据放在url 中)。

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": ""
}

【讨论】:

    【解决方案2】:

    只要发送Content-Length 标头并设置为0,发送带有空正文的POST 请求是完全合法的。 请求 通常计算Content-Length 标头的值。您观察到的行为可能是由于问题223 - 缺少内容长度。 尽管该错误尚未关闭,但看起来问题已修复:

    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": ""
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多