Calculating content length with Python
I am trying to make a post, but every time I did it I was getting a 411 response error. I am using the requests library in python.
In [1]: r.post(url)
Out[1]: <Response [411]>
So I have specified the content length h = {'content-length' : '0'}
and will try again.
In [2]: r.post(url,h)
Out[2]: <Response [200]>
So great, I get success, however none of the information is posted.
I think I need to compute the length of the content, which makes sense as it might be "clipping" the post.
So my question, given the url www.example.com/import.php?key=value&key=value
, how can I calculate content-length
? (if possible in python)
source to share
It looks like you are using a method post
with no argument data
(but put the data in the url).
Take a look at an example from the official 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": ""
}
source to share
Sending a request POST
with an empty body is perfectly legal as long as the header is Content-Length
sent and set to 0
. Queries usually compute a value for the header Content-Length
. The behavior you are seeing is probably related to issue 223 - content length is missing. Although the bug is not closed, it looks like the problem has been fixed:
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": ""
}
source to share