如何使用requests库发送XML请求体?

69
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

这些组合似乎不起作用。

由于某种原因,标头没有设置。


1
请解释一下“不起作用”的含义。包括错误信息、期望结果和实际结果等。 - Martijn Pieters
5
(){}[]括号内,您不需要使用\反斜杠续行符。去掉它们不会解决问题,但会使代码更易于阅读和维护。 - Martijn Pieters
请用英语说明您想要做什么,而不仅仅是代码。 - Lukas Graf
2个回答

138

直接发送XML字节:

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

输出

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

Requests可以用来发送使用xml.etree.ElementTree生成的XML正文吗? - Stevoisiak
@StevenVascellaro,无论是什么生成XML,只要它是一个字节串就可以。 - jfs

5

使用直接的XML而不是字典进行传递。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接