Java 如何使用Rest-Assured请求POST-API发送令牌和主体值?

Java 如何使用Rest-Assured请求POST-API发送令牌和主体值?,java,cucumber,rest-assured,qa,Java,Cucumber,Rest Assured,Qa,我正在尝试使用Rest-Assured和Java为postapi创建一个测试自动化。 此POST API的主体为Application/JSON,如下所示: { "customer":{ "email": "teste@mailinator.com" }, "password":"Teste@12" } 为了发出这个请求,我使用了下面的代码,但它返回状态代码“400”,但我在邮递员上发送了相同的信息,它返回“200”: } 结构正确吗?你觉得少了什么?谢

我正在尝试使用Rest-Assured和Java为postapi创建一个测试自动化。 此POST API的主体为Application/JSON,如下所示:

{
    "customer":{
        "email": "teste@mailinator.com"
    },
    "password":"Teste@12"
}
为了发出这个请求,我使用了下面的代码,但它返回状态代码“400”,但我在邮递员上发送了相同的信息,它返回“200”:

}


结构正确吗?你觉得少了什么?谢谢

您发送的邮件正文不正确

//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")
因此,您的有效负载将如下所示:

{“客户”:{password=密码,客户=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); 
Map emailContent=newhashmap();
emailContent.put(“电子邮件”example@example.com");
Map postContent=newhashmap();
postContent.put(“客户”,emailContent);
postContent.put(“密码”、“密码”);
给定().contentType(contentType.JSON)
.标题(“授权”、“持票人”+srtToken)
.with().body(后内容)
.when().post(srtAmbiente+srtAPI)
.then().statusCode(200);

您发送的邮件正文不正确

//This line will not serialize HashMap to JSON, but call toString()
.body("{\"customer\":" +postContent+ "}")
因此,您的有效负载将如下所示:

{“客户”:{password=密码,客户=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); 
Map emailContent=newhashmap();
emailContent.put(“电子邮件”example@example.com");
Map postContent=newhashmap();
postContent.put(“客户”,emailContent);
postContent.put(“密码”、“密码”);
给定().contentType(contentType.JSON)
.标题(“授权”、“持票人”+srtToken)
.with().body(后内容)
.when().post(srtAmbiente+srtAPI)
.then().statusCode(200);

是否有400代码的错误消息?能否为400代码添加响应正文?您可以通过在.post(srtAmbiente+srtAPI)之后添加.prettyPeek()来打印响应,而且您不需要添加内容类型头,因为您已经在此处指定了它。contentType(contentType.JSON)是否有400代码的错误消息?您可以为400代码添加响应正文吗?您可以通过在.post(srtAmbiente+srtAPI)之后添加.prettyPeek()来打印响应,而且您不需要添加内容类型头,因为您已经在此处指定了它。contentType(contentType.JSON)您还可以使用JSONObject而不是Map-您还可以使用JSONObject而不是Map-