2012-07-09 44 views
4

我有用於測試的VMware安裝程序。我創建了一個用戶abc/abc123來訪問組織URL「http:// localhost/cloud/org/MyOrg」。我想訪問VCloud的RestAPI。我試過RestClient插件firefox。它的工作正常。VCloud Director用於Python中RestAPI的Org用戶身份驗證

現在我試着用python代碼。

url = 'https://localhost/api/sessions/' 
req = urllib2.Request(url) 
base64string = base64.encodestring('%s:%s' % ('[email protected]', 'abc123'))[:-1] 
authheader = "Basic %s" % base64string 
req.add_header("Authorization", authheader) 
req.add_header("Accept", 'application/*+xml;version=1.5') 

f = urllib2.urlopen(req) 
data = f.read() 
print(data) 

這是我從stackoverflow得到的代碼。但對於我的例子,它給「urllib2.HTTPError:HTTP錯誤403:禁止」錯誤。

我也嘗試了相同的HTTP認證。

回答

5

做了一些Google搜索之後,我找到了來自https://stackoverflow.com/a/6348729/243031這個職位的解決方案。我改變了我的可用性的代碼。我發佈答案,因爲如果某人有同樣的錯誤,那麼他會直接得到答案。

我改變的代碼是:

import urllib2 
import base64 

# make a string with the request type in it: 
method = "POST" 
# create a handler. you can specify different handlers here (file uploads etc) 
# but we go for the default 
handler = urllib2.HTTPSHandler() 
# create an openerdirector instance 
opener = urllib2.build_opener(handler) 
# build a request 
url = 'https://localhost/api/sessions' 
request = urllib2.Request(url) 
# add any other information you want 
base64string = base64.encodestring('%s:%s' % ('[email protected]', 'abc123'))[:-1] 
authheader = "Basic %s" % base64string 
request.add_header("Authorization", authheader) 
request.add_header("Accept",'application/*+xml;version=1.5') 

# overload the get method function with a small anonymous function... 
request.get_method = lambda: method 
# try it; don't forget to catch the result 
try: 
    connection = opener.open(request) 
except urllib2.HTTPError,e: 
    connection = e 

# check. Substitute with appropriate HTTP code. 
if connection.code == 200: 
    data = connection.read() 
    print "Data :", data 
else: 
    print "ERRROR", connection.code 

希望這將幫助一些一誰想要發送沒有數據POST請求。