【问题标题】:Python httplib POST request and proper formattingPython httplib POST 请求和正确的格式
【发布时间】:2012-07-30 00:13:50
【问题描述】:

我目前正在研究一种与安装了 RESTful 网络服务的数据库网站交互的自动化方式。我在弄清楚如何使用 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"/>')

但这似乎是完全错误的。当涉及到 web 服务接口时,我从来没有真正做过 python,所以我的主要问题是我应该如何使用 httplib 来发送 POST 请求,尤其是其中的 XML 格式部分?任何帮助表示赞赏。

【问题讨论】:

    标签: python rest post httplib


    【解决方案1】:

    您需要在发送数据之前设置一些请求标头。例如,内容类型为“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

    你可能会有一些想法。

    【讨论】:

    • 如果您的端点使用 SSL,请确保将 webservice = httplib.HTTP(HOST) 更改为 webservice = httplib.HTTPS(HOST) 否则您将超时
    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多