有沒有人有一個使用Python向RESTful API發送XML POST請求的簡單示例?我試圖在Harvest API中使用urllib2 Python庫來「創建一個新項目」,但沒有運氣。有效載荷變量是一個有效的XML文檔那是他們的文檔的近複製/粘貼(下創建新項目的標題),如下圖所示:XML POST REST使用Python的請求
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(狀態OK),而不是響應代碼201(創建)......這是嘉實支持你們一個問題嗎?
任何人有任何提示將不勝感激。
謝謝, 傑夫。