带有请求的 POST XML 文件 [英] POST XML file with requests

查看:33
本文介绍了带有请求的 POST XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到:

<error>You have an error in your XML syntax...

当我运行这个 python 脚本时,我刚刚写了(我是新手)

when I run this python script I just wrote (I'm a newbie)

import requests

xml = """xxx.xml"""

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

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

print (r.content);

这里是xxx.xml的内容

Here is the content of the 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>

我知道 xml 是有效的,因为我对 perl 脚本使用了相同的 xml,并且正在打印内容.

I know that the xml is valid because I use the same xml for a perl script and the contents are being printed back.

任何帮助将不胜感激,因为我对 python 非常陌生.

Any help will greatly appreciated as I am very new to python.

推荐答案

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

You want to give the XML data from a file to requests.post. But, this function will not open a file for you. It expects you to pass a file object to it, not a file name. You need to open the file before you call requests.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, headers=headers)

print (r.content);

这篇关于带有请求的 POST XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆