java - 如何使用 Rest-Assured 请求 POST API 发送令牌和正文值?
问题描述
我正在尝试使用 Rest-Assured 和 Java 为 POST API 创建测试自动化。此 POST API 的主体为 Application/JSON,如下所示:
{
"customer":{
"email": "teste@mailinator.com"
},
"password":"Teste@12"
}
为了提出这个请求,我使用了以下代码,但它返回状态代码“400”,但我在 Postman 上发送相同的信息,它返回“200”:
@And("envio as informacoes da chamada: (.*), (.*), (.*), (.*) e (.*)")
public void enviarDados (String srtEmail, String srtSenha, String srtAmbiente, String srtAPI, String srtToken) {
HashMap<String,String> postContent = new HashMap<String,String>();
postContent.put("email", srtEmail);
postContent.put("password", srtSenha);
//System.out.println("{\"customer\":" +postContent+ "}");
given().contentType(ContentType.JSON).header("Authorization", "Bearer"+srtToken).header("Content-Type", "application/json").
//with().body(postContent).
with().body("{\"customer\":" +postContent+ "}").
when().post(srtAmbiente+srtAPI).
then().statusCode(200);
}
“400”响应是:
{
"status": 400,
"message": "Malformed request",
"additional_error": ""
}
结构对吗?您认为缺少什么?谢谢!
解决方案
您使用 POST 发送的正文不正确。
//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")
结果,您的有效负载将如下所示:
{“客户”:{密码=密码,客户=example@example.com}}
这不是有效的 JSON。尝试这个:
Map<String, String> emailContent = new HashMap<>();
emailContent.put("email", "example@example.com");
Map<String, Object> postContent = new HashMap<>();
postContent.put("customer", emailContent);
postContent.put("password", "password");
given().contentType(ContentType.JSON)
.header("Authorization", "Bearer "+srtToken)
.with().body(postContent)
.when().post(srtAmbiente+srtAPI)
.then().statusCode(200);
推荐阅读
- makefile - mingw32-make.exe:*** 缺少分隔符。停止
- c# - 在 C# Interactive 中使用控制台方法时出现“句柄无效”错误
- php - 按日期过滤 API 返回的数据
- excel - 如何修改最初在录制的宏中定义的文件的名称?
- kubernetes - 我可以在同一部署的 pod 中安装不同的主机吗?
- spring-boot - 未找到网关对服务的调用
- java - 在没有注释的 Spring MVC 控制器的 JSON 主体中强制对字符串值进行全局验证
- terraform - 即使 user_data 失败,Terraform 也会报告创建的 aws_instance
- c++ - 类构造中的 C++ 内存泄漏
- python - 创建自定义网络抓取工具来计算 python 中的唯一单词