简体   繁体   English

如何发送带有Python请求的XML ElementTree?

[英]How do I send an XML ElementTree with Python Requests?

I want to send an XML POST request using the Python 3 Requests library. 我想使用Python 3 Requests库发送XML POST请求。

When I create my XML body as a plaintext string, I am able to send XML bytes to the server without any issues. 当我将XML正文创建为纯文本字符串时,可以将XML字节发送到服务器而没有任何问题。 However, if I send my request as an ElementTree.Element , the server responds with the error message " Premature end of file ". 但是,如果我以ElementTree.Element发送请求,则服务器将以错误消息“ 文件的结尾过早 ”进行响应。

Writing XML as plaintext (works) 以纯文本形式编写XML(有效)

import requests

root = """<?xml version = '1.0'?>
          <Kronos_WFC version = '1.0'> </Kronos_WFC>"""
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC version="1.0" WFCVersion="6.3.13.362" TimeStamp="10/30/2017 12:19PM GMT-04:00"></Kronos_WFC>

Building XML with ElementTree (fails) 使用ElementTree构建XML(失败)

from xml.etree import ElementTree as ET
import requests

root = ET.Element("Kronos_WFC", version="1.0")
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC>
#    <Response Status="Failure" ErrorCode="-1" Message="Premature end of file.">
#    </Response></Kronos_WFC>

When I tried printing my XML ElementTree to debug, I found that Python was interpreting it as an object, rather than as parsable text. 当我尝试打印XML ElementTree进行调试时,我发现Python会将其解释为对象,而不是可解析的文本。 I suspect that this may be the cause of the issue. 我怀疑这可能是问题的原因。

root = ET.Element("Kronos_WFC", version="1.0")
print(root)

# Output:
# <Element 'Kronos_WFC' at 0x013492D0>

Ideally I would like to build my XML POST request using ElementTree.Element , then send it to an API using Requests. 理想情况下,我想使用ElementTree.Element构建我的XML POST请求,然后使用Requests将其发送到API。

How can I send an XML ElementTree.Element to a server using Python Requests? 如何使用Python请求将XML ElementTree.Element发送到服务器?

Use ElementTree.tostring() to create a string representation of the xml. 使用ElementTree.tostring()创建xml的字符串表示形式。

requests.post(
    'http://localhost/wfc/XmlService', 
    data=ET.tostring(root), 
    headers=headers
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM