接口发送 xml 格式的数据如何测试?

本贴最后更新于 1361 天前,其中的信息可能已经事过景迁

Snipaste_2020-03-02_14-31-35.jpg

什么是 xml ?

xml 是一种和 html 非常类似的语言,采取一定的格式展示数据。比如:

<note>
<to></to>
<from></from>
<heading>提醒</heading>
<body>今晚八点,不见不散</body>
</note>

这个例子非常形象的指明:


xml 和 html 的区别


接口当中为什么会有 xml ?

xml 的作用和 json 实在是太像了。 通过 json, 可以代替 xml 的作用:

{
    "note": {
        "to": "你",
        "from": "我",
        "heading": "提醒",
        "body": "今晚八点,不见不散",
    }
}

以前,接口通常会采用 xml 来传输数据。而现在,大多数接口都是采用 json 进行数据传递, xml 已经被冷落了,主要的原因是:

但是,还是有一些公司的接口是采用 xml, 比如大名鼎鼎的微信,很多接口还是采用 xml。 原因是 xml 在一些特定领域还占有一些优势:

xml 和 json 的区别,归根结底在于他们表达数据的方式不同,xml 用的是树形结构, json 对应的是 hash 映射。


使用工具测试 xml 数据接口

接口发送 xml 格式的数据和发送 json 几乎一样,只需要把格式改成 xml 就可以了。

采用 postman 接口测试工具 往接口https://httpbin.org/post 发送以下 xml 数据:

<note>
<to>you</to>
<from>yuz</from>
<heading>hey</heading>
<body>8 tonight</body>
</note>

postman 数据填写:
postman发送xml数据

通过 fiddler 抓包可以查看到发送的数据:
postman发送xml数据fiddler抓包.png

通过 postman 查看返回结果:
postman发送xml数据结果.png

通过上面的例子得出:


使用 python 编程语言测试 xml 数据接口

使用 python 语言的 requests 库可以很方便的发送 xml 格式的数据,只需要把请求头格式换成 application/xml 就可以了:

import requests

xml_data = """
<note>
<to>you</to>
<from>yuz</from>
<heading>hey</heading>
<body>8 tonight</body>
</note>
"""
header = {"content-type": "application/xml"}
res = requests.post('http://httpbin.org/post', data=xml_data, headers=header)

xml 数据存储在文件当中

测试数据如果不是通过在代码中直接传递,而是通过文件形式存储,则使用 python 当中的 open 函数直接读取。
postman发送xml数据文件.png
相应代码:

xml_data = open('data.xml').read()
header = {"content-type": "application/xml"}
res = requests.post('http://httpbin.org/post', data=xml_data, headers=header)
  • Python
    101 引用 • 234 回帖 • 1 关注
1 操作
yuze 在 2020-08-06 17:45:06 更新了该帖
回帖
请输入回帖内容 ...