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();
    }
}

``

喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一键三连哦。[更多技术文章](https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=bokeyuan&timestamp=1652247797&author=BB)
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/chengzi-ceba/p/16555372.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!