4

我有用于测试的 VMware 设置。我创建了一个用户 abc/abc123 来访问 Org url “http://localhost/cloud/org/MyOrg”。我想访问 VCloud 的 RestAPI。我尝试在firefox中使用RestClient插件。它工作正常。

现在我尝试使用 python 代码。

url = 'https://localhost/api/sessions/'
req = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % ('abc@MyOrg', '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 身份验证。

4

1 回答 1

5

做了一些谷歌搜索后,我从帖子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' % ('abc@MyOrg', '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请求的人。

于 2012-07-10T08:12:52.637 回答