使用Python进行XML POST REST请求
有没有人能给个简单的例子,教我怎么用Python发送一个XML格式的POST请求到RESTful API?我想用urllib2这个Python库在Harvest API里“创建一个新项目”,但一直没成功。payload变量是一个有效的XML文档,几乎是直接复制他们文档里的内容(在“创建新项目”那一节):
http://www.getharvest.com/api/projects
这是我尝试执行的代码。
def postRequest():
""" Makes POST request to url, and returns a response. """
url = 'http://subdomain.harvestapp.com/projects'
opener = urllib2.build_opener()
opener.addheaders = [('Accept', 'application/xml'),
('Content-Type', 'application/xml'),
('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]),
('User-Agent', 'Python-urllib/2.6')]
req = urllib2.Request(url=url, data=payload)
assert req.get_method() == 'POST'
response = self.opener.open(req)
print response.code
return response
我收到的响应代码是200(状态正常),而不是201(已创建)……这是不是应该问Harvest的支持团队呢?
如果有人能给点提示,我会非常感激。
谢谢,
杰夫。
2 个回答
1
你在其他地方都使用了本地的打开器,只有在创建响应的那一行用了self.opener
,这看起来就是问题所在。
1
通常情况下,即使返回201状态码更合适,很多时候也会返回200状态码。你确定即使你得到了一个“正确”的响应,请求也没有被正确处理吗?