【问题标题】:How can I send an xml body using requests library?如何使用请求库发送 xml 正文?
【发布时间】:2012-09-12 15:47:17
【问题描述】:
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

这些组合似乎不起作用。

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

【问题讨论】:

  • 解释“似乎不起作用”。错误信息、预期结果和实际结果等?
  • () 括号和{}[] 括号内,您不需要使用\ 反斜杠延续。删除不会解决您的问题,但会使您的代码更易于阅读和维护。
  • 请用英文说明你要做什么,而不仅仅是代码。

标签: python python-requests


【解决方案1】:

直接传入 XML 而不是字典。

【讨论】:

    【解决方案2】:

    直接发送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>"
    }
    

    【讨论】:

    • 可以使用请求发送使用xml.etree.ElementTree 生成的 XML 正文吗?
    • @StevenVascellaro 只要它是一个字节串,生成 xml 的内容并不重要
    猜你喜欢
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2014-10-08
    • 2018-09-04
    相关资源
    最近更新 更多