2012-03-13 213 views
3

我試圖發表一篇文章,但是每次我做到這一點,我都會得到一個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://stackoverflow.com/a/3854983/5354673) – 2017-02-26 12:44:50

回答

0

看起來很奇怪,您使用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": "" 
} 
1

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