0

I'm attempting to make a bot, although the post request requires to be in XML, I have no experience dealing with XML and I'd like your help.

The request payload looks a bit like this:

------WebKitFormBoundaryyXmSIiVhzetQj7u9
Content-Disposition: form-data; name="Name"

asdafa
------WebKitFormBoundaryyXmSIiVhzetQj7u9
Content-Disposition: form-data; name="Description"


------WebKitFormBoundaryyXmSIiVhzetQj7u9
Content-Disposition: form-data; name="Genre"

All
------WebKitFormBoundaryyXmSIiVhzetQj7u9
Content-Disposition: form-data; name="thumbnailImageFile"; filename=""
Content-Type: application/octet-stream

How would I replicate that in python?

I've tried simple things such as

create = s.post(url='https://www.url.com/', data=xml)

I've also tried having a header like {'Content-Type': 'application/xml'} and I've had no success.

  • Possible duplicate of [How can I send an xml body using requests library?](https://stackoverflow.com/questions/12509888/how-can-i-send-an-xml-body-using-requests-library) – Evhz Jun 23 '18 at 08:06
  • That's not XML. – larsks Jun 23 '18 at 10:07

1 Answers1

0

It looks as if you're trying to submit form data using the multipart/form-data format. You can do this with the requests library by making use of the files parameter, which is documented in the "Post a multipart encoded file" section of the documentation, which shows the following example:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> result = requests.post(url, files=files)

This would result in the following data being sent to the server:

Content-type: multipart/form-data; boundary=66702e4da1364ad181a6ef1437ed39ce

--66702e4da1364ad181a6ef1437ed39ce
Content-Disposition: form-data; name="file"; filename="report.csv"

some,data,to,send
another,row,to,send

--66702e4da1364ad181a6ef1437ed39ce--

As you can see, this is almost what you want, except it includes erroneous filename parameters. These will not be included if you pass None as the filename. To make it easier to send dictionaries using this format, I wrote the following helper method:

def dict_to_multipart(d):                                                                 
    return {k: (None, v) for k, v in d.items()}                                            

If we have data that looks like this:

data = {'Name': 'asdf', 'Genre': 'all'}

We can send it like this:

result = requests.post('https://requestbin.fullcontact.com/1oso55v1',
                       files=dict_to_multipart(data))

The data that gets sent to the webserver in this case looks like:

Content-type: multipart/form-data; boundary=60eaef81347645b4b1e9a2f02634baca

--60eaef81347645b4b1e9a2f02634baca
Content-Disposition: form-data; name="Genre"

all
--60eaef81347645b4b1e9a2f02634baca
Content-Disposition: form-data; name="Name"

asdf
--60eaef81347645b4b1e9a2f02634baca--
larsks
  • 277,717
  • 41
  • 399
  • 399