Reputation: 65
I'm trying to create a POST request in rest assured java but receiving HTTP Status 400 – Bad Request. Have tried below two approaches and the same API is working fine in postman. I'm using 4.1.2 rest assured in pom.xml
curl --location --request POST 'http://localhost:8080//api/v1/planning/trips?pageNumber=1&pageSize=40'
--header 'authority: http://localhost:8080'
--header 'authorization: Bearer e8c108d6-c380-4715-849b-b6eccd8d2045'
--header 'origin: http://localhost:8080'
--header 'referer: http://localhost:8080'
--header 'Content-Type: application/json;charset=UTF-8'
--data-raw '{ "endPlacementTimestamp": 1594994096206, "startPlacementTimestamp": 1593525296206 }'
Approach 1:
RestAssured.baseURI="http://localhost:8080";
RequestSpecification httpRequest = RestAssured.given();
httpRequest.header("authority","http://localhost:8080");
httpRequest.header("authorization","Bearer e8c108d6-c380-4715-849b-b6eccd8d2045");
httpRequest.header("Content-Type","application/json;charset=UTF-8");
httpRequest.header("origin","http://localhost:8080");
httpRequest.header("referer","http://localhost:8080");
JSONObject requestParams = new JSONObject();
requestParams.put("endPlacementTimestamp", "1594994096206");
requestParams.put("startPlacementTimestamp","1593525296206");
httpRequest.body(requestParams.toJSONString());
Response response = httpRequest.request(Method.POST,"planning/trips?pageNumber=1&pageSize=40");
int statusCode = response.getStatusCode();
// Assert.assertEquals(statusCode, "200");
// Retrieve the body of the Response
ResponseBody body = response.getBody();
Approach 2:
String body= "{\n" +
" \"endPlacementTimestamp\": 1594994096206,\n" +
" \"startPlacementTimestamp\": 1593525296206\n" +
"}";
RestAssured.baseURI="http://localhost:8080//api/v1/";
Response response = given()
.contentType("application/json")
.header("authorization","Bearer e8c108d6-c380-4715-849b-b6eccd8d2045")
.header("origin","http://localhost:8080")
.header("referer","http://localhost:8080")
.body(body)
.post("planning/trips?pageNumber=1&pageSize=40");[![enter image description here][1]][1]
Upvotes: 0
Views: 5219
Reputation: 2774
Here's a simplified version of it, I have added a JSONObject here so you don't hardcode the payload in the body()
RestAssured.baseURI = "http://localhost:8080";
RequestSpecification requestSpec = new RequestSpecBuilder().addHeader("authority", "http://localhost:8080")
.addHeader("authorization", "Bearer e8c108d6-c380-4715-849b-b6eccd8d2045")
.addHeader("origin", "http://localhost:8080").addHeader("referer", "http://localhost:8080")
.addHeader("Content-Type", "application/json").build();
JSONObject payload = new JSONObject();
body.put("endPlacementTimestamp", 1594994096206L);
body.put("startPlacementTimestamp", 1593525296206L);
given().log().all().spec(requestSpec).queryParam("pageNumber", "1").queryParam("pageSize", "40").body(payload)
.post("/api/v1/planning/trips");
Upvotes: 1
Reputation: 29
In approach1:
Upvotes: 0