带请求的POST XML文件

Bio*_*Rod 1 python python-requests

我越来越:

<error>You have an error in your XML syntax...
Run Code Online (Sandbox Code Playgroud)

当我运行此python脚本时,我刚刚写过(我是新手)

import requests

xml = """xxx.xml"""

headers = {'Content-Type':'text/xml'}

r = requests.post('https://example.com/serverxml.asp', data=xml)

print (r.content);
Run Code Online (Sandbox Code Playgroud)

这是xxx.xml的内容

<xml>
<API>4.0</API>
<action>login</action>
<password>xxxx</password>
<license_number>xxxxx</license_number>
<username>xxx@xyz.com</username>
<training>1</training>
</xml>
Run Code Online (Sandbox Code Playgroud)

我知道xml是有效的,因为我为perl脚本使用了相同的xml,并且内容被打印回去。

任何帮助将不胜感激,因为我是python的新手。

小智 6

您想要将XML数据从文件提供给requests.post。但是,此功能不会为您打开文件。它希望您将文件对象而不是文件名传递给它。您需要在调用request.post之前打开文件。

尝试这个:

import requests

# Set the name of the XML file.
xml_file = "xxx.xml"

headers = {'Content-Type':'text/xml'}

# Open the XML file.
with open(xml_file) as xml:
    # Give the object representing the XML file to requests.post.
    r = requests.post('https://example.com/serverxml.asp', data=xml)

print (r.content);
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,“headers”在这里没有被使用。它是在“POST”调用中定义的而不是发送的。您可以同时发送: `requests.post('&lt;address&gt;', headers=headers, data=xml)` 我检查这是真的。不包含它时我没有收到错误,但我认为我看到了更快的结果...无论如何,如果只是定义它而不传递它,就会在 Python 中执行一些我不知道的神奇操作不要让我感到惊讶。这个答案确实帮助我走得更远。这是我的代码审查:)我看到定义了OP,但也没有使用它。 (3认同)