如何使用请求库发送 xml 正文? [英] How can I send an xml body using requests library?

查看:50
本文介绍了如何使用请求库发送 xml 正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

直接发送xml字节即可:

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

输出

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

这篇关于如何使用请求库发送 xml 正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆