发送Xml请求

2024-10-03 06:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python lol中总共花了30分钟,所以在回答lol时要考虑到这一点:

我试图发送一个带有主体的httppost请求并读取响应。我在Windows10上使用Python3.6.5。到目前为止,我得到的是:

进口http.客户端 进口xml.dom.minidom在

HOST = "www.mysite.com"
API_URL = "/service"

def do_request(xml_location):

request = open(xml_location, "r").read()

webservice = http.client.HTTPConnection(HOST)

webservice.request("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()
resultxml = xml.dom.minidom.parseString(result)

print (statuscode, statusmessage, header)
print (resultxml.toprettyxml())

with open("output-%s" % xml_location, "w") as xmlfile:
    xmlfile.write(resultxml.toprettyxml())

do_request("test.xml")

在测试.xml包含XML请求。当我运行时,我得到一个错误:

^{pr2}$

Tags: apiwebhttphosturlrequestservicelocation
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:34

您的问题是您混淆了^{}和{a2}方法。(毫不奇怪,考虑到文档的简洁性和稀疏性……Python中的大多数模块的文档都比这要好得多,所以不要让这让您担心未来。)

request方法是一个方便的函数,可以一次性添加请求行、所有头和数据。这样做之后,添加头就太晚了,因此会出现错误消息。在

所以,你可以用任何一种方法来解决它。在


(1)将其更改为使用putrequest。我知道在文档中没有使用putrequestputheader的例子,但它看起来像这样:

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)

(2)将其更改为使用request。文档中的所有示例都是这样做的;您只需要建立一个标题dict来传递给它:

^{pr2}$

(3)在文件顶部阅读:

This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib.request uses it to handle URLs that use HTTP and HTTPS.

See also The Requests package is recommended for a higher-level HTTP client interface.

对于大多数实际情况,如果您可以使用第三方库,则可以使用requests,如果不能,则使用urllib.request。这两种方法都更简单,而且有更好的文档记录。在

相关问题 更多 >