json 是一种轻量级的传输数据格式,用于数据交互。json 请求类型的请求头中的 Content-Type 对应为 application/json 。碰到这种类型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解决。
实战演示
在 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 中,使用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();
}
}
哈喽,喜欢这篇文章的话烦请点个赞哦!万分感谢~(^▽^)PS:有问题可以联系我们哦~v ceshiren001
复制“下方链接”,提升测试核心竞争力!
[更多技术文章分享和免费资料领取]('
https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=toutiao×tamp=1659492729&author=Muller')