2012-07-30 62 views
0

我目前正在處理一個自動化的方式來與安裝了REST風格的web服務的數據庫網站進行交互。我遇到的問題是如何正確地發送使用python的以下站點中列出的請求的正確格式。 https://neesws.neeshub.org:9443/nees.htmlPython httplib POST請求和正確格式化

具體的例子是這樣的:

POST https://neesws.neeshub.org:9443/REST/Project/731/Experiment/1706/Organization 

<Organization id="167"/> 

最大的問題是,我不知道在哪裏把上面的XML格式的一部分。我想發送上面的python HTTPS請求,到目前爲止,我一直在嘗試以下結構。

>>>import httplib 
>>>conn = httplib.HTTPSConnection("neesws.neeshub.org:9443") 
>>>conn.request("POST", "/REST/Project/731/Experiment/1706/Organization") 
>>>conn.send('<Organization id="167"/>') 

但這似乎是完全錯誤的。我從來沒有真正做過Python的Web服務接口,所以我的主要問題是我該如何使用httplib發送POST請求,尤其是XML格式的一部分?任何幫助表示讚賞。

回答

0

您需要在發送數據之前設置一些請求標頭。例如,內容類型爲'text/xml'。結帳的幾個例子,

Post-XML-Python-1

具有這種代碼例如:

import sys, httplib 

HOST = www.example.com 
API_URL = /your/api/url 

def do_request(xml_location): 
"""HTTP XML Post requeste""" 
request = open(xml_location,"r").read() 
webservice = httplib.HTTP(HOST) 
webservice.putrequest("POST", API_URL) 
webservice.putheader("Host", HOST) 
webservice.putheader("User-Agent","Python post") 
webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"") 
webservice.putheader("Content-length", "%d" % len(request)) 
webservice.endheaders() 
webservice.send(request) 
statuscode, statusmessage, header = webservice.getreply() 
result = webservice.getfile().read() 
    print statuscode, statusmessage, header 
    print result 

do_request("myfile.xml") 

Post-XML-Python-2

你可能會得到一些想法。