json 是一种轻量级的传输数据格式,用于数据交互。json 请求类型的请求头中的 Content-Type 对应为 application/json。碰到这种类型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解决。
实战演示
Python演示代码
在 Python 中,使用 json 关键字参数发送 json 请求并传递请求体信息。
>>> import requests
>>> r = requests.post(
'https://httpbin.ceshiren.com/post',
json = {'key':'value'})
>>> r.request.headers
{'User-Agent': 'python-requests/2.22.0',
'Accept-Encoding': 'gzip, deflate',\
'Accept': '*/*', 'Connection': 'keep-alive',
'Content-Length': '16',\
'Content-Type': 'application/json'}
如果请求的参数选择是json,那么Content-Type自动变为application/json。
Java 演示代码
在 Java 中,使用contentType()方法添加请求头信息,使用body()方法添加请求体信息。
import static org.hamcrest.core.IsEqual.equalTo;
import static io.restassured.RestAssured.*;
public class Requests {
public static void main(String[] args) {
String jsonData = "{\"key\": \"value\"}";
//定义请求头信息的contentType为application/json
given().contentType("application/json").
body(jsonData).
when().
post("https://httpbin.ceshiren.com/post").
then().body("json.key", equalTo("value")).log().all();
}
}
喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一 键三连哦!
软件测试工程师自学教程:
这才是2022最精细的自动化测试自学教程,我把它刷了无数遍才上岸字节跳动,做到涨薪20K【值得自学软件测试的人刷】
软件测试工程师月薪2W以上薪资必学技能 — Python接口自动化框架封装.
美团面试真题_高级测试25K岗位面试 — 软件测试人都应该看看
软件测试必会_Jmeter大厂实战 — 仅6步可实现接口自动化测试