web-dev-qa-db-fra.com

Comment puis-je envoyer un corps XML à l'aide de la bibliothèque de requêtes?

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

Ces combinaisons ne semblent pas fonctionner.

Les en-têtes ne sont pas définis pour une raison quelconque.

35
Dimitris Leventeas

Il suffit d’envoyer les octets xml directement:

#!/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

Sortie

{
  "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>"
}
85
jfs

Transmettez le XML droit au lieu d'un dictionnaire.

1
root