Python httplib POST请求和正确的格式

时间:2012-07-30 00:13:50

标签: python rest post httplib

我目前正致力于以自动方式与安装了RESTful webservices的数据库网站进行交互。我有问题弄清楚如何使用python正确发送在以下网站中列出的请求的正确格式。 https://neesws.neeshub.org:9443/nees.html

具体的例子如下:

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"/>')

但这似乎完全错了。在涉及webservices接口时,我从来没有真正完成python所以我的主要问题是我应该如何使用httplib来发送POST请求,特别是XML格式化部分?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您需要在发送数据之前设置一些请求标头。例如,content-type为'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

你可能会有所了解。