Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 884
tshauck Avatar asked Mar 13 '12 22:03

tshauck


People also ask

How do you calculate content length?

As bytes are represented with two hexadecimal digits, one can divide the number of digits by two to obtain the content length (There are 12 hexadecimal digits in "48656c6c6f21" which equates to six bytes, as indicated in the header "Content-Length: 6" sent from the server).

How do I add content length to a header in Python?

To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.

Is content length needed?

The Content-Length is optional in an HTTP request. For a GET or DELETE the length must be zero. For POST, if Content-Length is specified and it does not match the length of the message-line, the message is either truncated, or padded with nulls to the specified length.

What is content length header?

The Content-Length header indicates the size of the message body, in bytes, sent to the recipient.


1 Answers

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": ""
}
like image 169
Leonid Shvechikov Avatar answered Sep 30 '22 01:09

Leonid Shvechikov