Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send an xml body using requests library?

def request():
    #encoded_xml = urllib.urlencode({'XML': read_xml()})
    #encoded_xml = read_xml()
    headers = {'Authorization': AUTH_TOKEN,\
               'developerToken': DEVELOPER_TOKEN,\
               'clientCostumerID': CLIENT_ID}
    content = {'__rdxml': encoded_xml}
    #content = encoded_xml
    #content = {'__rdxml': read_xml2()}
    r = requests.post(URL, data=content,\
        headers=headers)
    return r

These combinations don't seem to work.

The headers are not set for some reason.

like image 526
Dimitris Leventeas Avatar asked Sep 20 '12 09:09

Dimitris Leventeas


People also ask

How do I send an XML request?

Send XML requests with the raw data type, then set the Content-Type to text/xml . After creating a request, use the dropdown to change the request type to POST. Open the Body tab and check the data type for raw. Click Send to submit your XML Request to the specified server.

How do you pass a body in a POST request in Python?

You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

How do I send XML data to a restful web service?

If you want to send XML data to the server, set the Request Header correctly to be read by the sever as XML. xmlhttp. setRequestHeader('Content-Type', 'text/xml'); Use the send() method to send the request, along with any XML data.

What is the Requests library used for?

The requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.


2 Answers

Just send xml bytes directly:

#!/usr/bin/env python2 # -*- coding: utf-8 -*- import requests  xml = """<?xml version='1.0' encoding='utf-8'?> <a>б</a>""" headers = {'Content-Type': 'application/xml'} # set what your server accepts print requests.post('http://httpbin.org/post', data=xml, headers=headers).text 

Output

{   "origin": "x.x.x.x",   "files": {},   "form": {},   "url": "http://httpbin.org/post",   "args": {},   "headers": {     "Content-Length": "48",     "Accept-Encoding": "identity, deflate, compress, gzip",     "Connection": "keep-alive",     "Accept": "*/*",     "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",     "Host": "httpbin.org",     "Content-Type": "application/xml"   },   "json": null,   "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>" } 
like image 95
jfs Avatar answered Oct 16 '22 08:10

jfs


Pass in the straight XML instead of a dictionary.

like image 31
root Avatar answered Oct 16 '22 10:10

root