2012-07-12 119 views
7

我使用的urllib2和urllib的圖書館在Python當使用urllib2請求URL時,爲什麼會出現「HTTP Error 405:Method Not Allowed」?

假設我有以下代碼

import urllib2 
import urllib 

url = 'http://ah.example.com' 
half_url = u'/servlet/av/jd?ai=782&ji=2624743&sn=I' 

req = urllib2.Request(url, half_url.encode('utf-8')) 
response = urllib2.urlopen(req) 
print response 

當我運行上面的代碼我收到以下錯誤

Traceback (most recent call last): 
    File "example.py", line 39, in <module> 
    response = urllib2.urlopen(req) 
    File "/usr/lib64/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/usr/lib64/python2.7/urllib2.py", line 398, in open 
    response = meth(req, response) 
    File "/usr/lib64/python2.7/urllib2.py", line 511, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/usr/lib64/python2.7/urllib2.py", line 436, in error 
    return self._call_chain(*args) 
    File "/usr/lib64/python2.7/urllib2.py", line 370, in _call_chain 
    result = func(*args) 
    File "/usr/lib64/python2.7/urllib2.py", line 519, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 405: Method Not Allowed 

任何人都可以讓我知道這裏發生了什麼,爲什麼它不工作

在此先感謝............

+0

@保羅:非常感謝編輯 – 2012-07-13 05:17:29

回答

13

您正在調用的服務器告訴您,您嘗試呼叫的URL不允許POST方法。

通過將URL的路徑部分作爲Request對象數據參數傳入,您將使其成爲POST而不是GET。

我懷疑你想發送一個GET請求,而不是:

req = urllib2.Request(url + half_url.encode('utf-8')) 
+0

我懷疑是UTF-8編碼的URL不URL編碼它可能是一個問題,雖然。 – geoffspear 2012-07-12 14:03:33

+0

@Wooble:不在OP中。 – 2012-07-12 14:04:07

+0

那麼的確如此,儘管在那個例子中'.encode('utf-8')'是一個無操作,因爲它已經是所有的ASCII碼了,並且保持不變。 – geoffspear 2012-07-12 14:05:13

相關問題