I'm trying to POST data to a URL using Pythons requests library.
If I try and do this by setting a multiline string variable which contains the post data in my script, everything works fine.
If I try to read in an external file with the same data in, the request fails on the application server I'm posting to, because it thinks there is invalid XML.
For example:
This works
starturl="http://myserver.example.com/location/where/I/post"
username=user
password=mypassword
# Set the XML data
xmldata="""<?xml version="1.0" encoding="utf-8"?>
(Lots more xml)
"""
# POST the job data
session = requests.Session()
request = session.post(starturl, auth=(username,password), data=xmldata, headers=post_headers)
Server side application processes the request just fine. However, if the only change I make is to read the xml data from an external file, this no longer works.
This does not work
xmlfile="/path/to/my/xmldata.xml"
xmldata = open(xmlfile,'r')
session = requests.Session()
request = session.post(start_url, auth=(username,password), data=xmldata.read(), headers=post_headers)
The server side application, then errors with:
"Data at the root level is invalid. Line 1, position 1"
When inspecting with wireshark I can see there is a difference in the request body of my POST. Three little dots are appearing from somewhere
When it works:
Content-Type: application/xml
Authorization: Basic c3BvdGFkbTpQQHNzdzByZA==
<?xml version="1.0" encoding="utf-8"?>
When it fails:
Content-Type: application/xml
Authorization: Basic c3BvdGFkbTpQQHNzdzByZA==
...<?xml version="1.0" encoding="utf-8"?>
I'm not sure what's causing the 3 leading dots to appear in the request body. I've inspected the source XML file, tried stripping newlines from it. Nothing seems to do the trick?
xmldatawithout reading it. See this part of documentation. Just userequest = session.post(starturl, auth=(username,password), data=xmldata, headers=post_headers)wherexmldatais opened file. However I am not sure if this will solve your problem.xmldata = open(xmlfile,'rb')As long as error can not be reproduced, there will be no exact answer.codecs.BOM_UTF8sequence ('\xef\xbb\xbf') and strip it out if it's there.