簡體   English   中英

如何發送帶有Python請求的XML ElementTree?

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

我想使用Python 3 Requests庫發送XML POST請求。

當我將XML正文創建為純文本字符串時,可以將XML字節發送到服務器而沒有任何問題。 但是,如果我以ElementTree.Element發送請求,則服務器將以錯誤消息“ 文件的結尾過早 ”進行響應。

以純文本形式編寫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>

使用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>

當我嘗試打印XML ElementTree進行調試時,我發現Python會將其解釋為對象,而不是可解析的文本。 我懷疑這可能是問題的原因。

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

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

理想情況下,我想使用ElementTree.Element構建我的XML POST請求,然后使用Requests將其發送到API。

如何使用Python請求將XML ElementTree.Element發送到服務器?

使用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