Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST XML file with requests

I'm getting:

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

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);

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>[email protected]</username>
<training>1</training>
</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.

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

like image 521
BioRod Avatar asked Jun 17 '26 02:06

BioRod


1 Answers

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.

Try this:

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);
like image 57
Tay Avatar answered Jun 19 '26 16:06

Tay