pythonhttphttp-headershttp-requestpython-requests

Calculating Content-Length with Python


I'm trying to make a post, however each time I did it, I would get a 411 response error. I'm using the requests library in python.

In [1]: r.post(url)
Out[1]: <Response [411]>

So then I specified the content length h = {'content-length' : '0'} and try again.

In [2]: r.post(url,h)
Out[2]: <Response [200]>

So great, I get a success, however none of the information is posted in.

I think I need to calculate the content-length, which makes sense as it could be "cutting-off" the post.

So my question is, given a url www.example.com/import.php?key=value&key=value how can I calculate the content-length? (in python if possible)


Solution

  • It looks strange that you use post method without the data argument (but put data in url).

    Look at the example from the 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": ""
    }