使用Python计算内容长度

使用Python计算内容长度

问题描述:

我试图发表一篇文章,但是每次我做到这一点,我都会得到一个411响应错误。我在Python中使用请求库。使用Python计算内容长度

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

那么我指定了内容长度h = {'content-length' : '0'},然后再试一次。

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

如此之大,我获得了成功,但是,没有一个信息发布英寸

我想我需要计算的内容长度,这是有道理的,因为它可以“切断“这个职位。

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

+1

它的工作,如果你只是用'urllib'? (我惊讶的是'request'不会自动填充'Content-Length'头部,因为它基于'httplib')。 – katrielalex 2012-03-13 22:19:15

+0

请添加关于您正在使用的请求版本的信息。还请包括导致411响应状态码的测试用例。 – 2012-04-18 20:44:20

+0

[访问该链接以获取您的查询的答案](http://*.com/a/3854983/5354673) – 2017-02-26 12:44:50

看起来很奇怪,您使用post方法而没有data参数(但将数据放入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": "" 
} 

发送POST请求空体是完全合法的,只要该Content-Length头正被发送并设置为0请求通常会计算出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": "" 
}