gpt4 book ai didi

java - 如何使用 Rest-Assured 请求 POST API 发送 token 和正文值?

转载 作者:行者123 更新时间:2023-12-02 01:33:37 24 4
gpt4 key购买 nike

我正在尝试使用 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+ "}")

因此,您的有效负载将如下所示:

{"customer":{password=password, customer=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);

关于java - 如何使用 Rest-Assured 请求 POST API 发送 token 和正文值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com