2012-07-30 58 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

你可能会得到一些想法。