When I execute the below code in a java file in normal java project in eclipse it is running successfully:
given()
.log().all()
.contentType("application/json")
.auth().basic(APIKEY, PASSWORD)
.body("{\"customName\":\"name\",\"customGender\":\"male\",\"customDateofBirth\":\"2010-12-08\",\"customRelationship\":\"child\"}")
.when()
.post("https://api.bamboohr.com/api/gateway.php/companyName/v1/employees/1420/tables/customDependants(IN)")
.then().assertThat().statusCode(200);
After executing successfully it adds a new record in the specified table;(customDependants(IN), the table here).
Whereas, when I run the same in a spring boot project am getting an error saying:
java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <400>.
FYI: I have tried with other request params in place of contentType("application/json")
like: headers("Content-Type", ContentType.JSON)
.
Error log:
HTTP/1.1 400 Bad Request Server: nginx Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive X-BambooHR-Error-Messsage: Malformed XML X-BambooHR-Error-Message: Malformed XML Cache-Control: no-cache Date: Tue, 31 Dec 2019 02:45:30 GMT X-BambooHR-Error-Message: Malformed XML X-BambooHR-Error-Messsage: Malformed XML
Request log:
Request method: POST
Request URI: https://api.bamboohr.com/api/gateway.php/companyName/v1/employees/1420/tables/customDependants%28IN%29
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/* Content-Type=application/json ; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body: {
"customName": "name",
"customGender": "male",
"customDateofBirth": "2010-12-08",
"customRelationship": "child"
}
Spring Boot code where I am getting this error:
private void employeeDependents(int empId) {
/*Employees Repository*/
TaBhr taBhr = taBhrRepository.findByBhrId(empId);
/*Grabbing an employee of given ID from Employees Repository*/
Optional<Employee> employee = employeeRepository.findById(taBhr.getEmpId());
Gson gson = new GsonBuilder().serializeNulls().create();
List<EmployeeDependent> list = employee.isPresent()
? employeeDependentRepository.findByDependentsEmpnumber(employee.get().getNumber())
: null;
if (list != null) {
for (EmployeeDependent employeeDependent : list) {
/*Sets the Data Transfer Object*/
EmployeeDependentDTO employeeDependentDTO = new EmployeeDependentDTO();
employeeDependentDTO.setFirstName(employeeDependent.getEdName());
employeeDependentDTO.setDateOfBirth(employeeDependent.getEdDateOfBirth());
employeeDependentDTO.setRelationship(employeeDependent.getDependentGender().getEdRelationshipType());
employeeDependentDTO.setGender(employeeDependent.getDependentGender().getGender());
TaBhr tabhr = taBhrRepository.findByEmpId(employee.get().getId());
if (tabhr != null) {
#LOG.info("BHR ID: {}", empId);#
given().log().all().contentType("application/json").auth()
.basic(APIKEY, PASSWORD)
.body(gson.toJson(employeeDependentDTO)).when()
.post("https://api.bamboohr.com/api/gateway.php/companyName/v1/employees/1420/tables/customDependants(IN)")
.then().log().ifError().assertThat().statusCode(200);
}
}
}
}
When I run, it goes till the LOG that is surrounded by #s and then when the API is hit, the response is Malformed XML. The value of gson.toJson(employeeDependentDTO)
is {"customName":"abcd","customGender":"male","customDateofBirth":"2010-12-08","customRelationship":"child"}
.
Moreover, here I set the content type as JSON and not XML and even the payload is in JSON format which works in postman and non-spring boot project.
FYI: All get requests are working perfectly in spring boot application and when I try to hit API with a post then only am getting the above error, whereas, if I execute the same in a non-spring application everything works fine. The same is working fine in postman.
Please help me with why it is failing to execute in spring boot application.
I have used an alternative solution here using HttpURLConnection in java and it is working perfectly, here is the code which replaces above Rest Assured code:
try {
String rawData = "{\"customName\":\"success\",\"customGender\":\"male\",\"customDateofBirth\":\"2010-12-08\",\"customRelationship\":\"child\"}";
String url = "https://api.bamboohr.com/api/gateway.php/companyName/v1/employees/1420/tables/customDependants(IN)";
URL obj = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection) obj.openConnection();
String userCredentials = APIKEY:PASSWORD;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setRequestProperty("Accept", "application/json");
myURLConnection.setDoOutput(true);
byte[] outputInBytes = rawData.getBytes("UTF-8");
OutputStream w = myURLConnection.getOutputStream();
w.write(outputInBytes, 0, outputInBytes.length);
w.close();
int responseCode = myURLConnection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response code : " + responseCode);
System.out.println(response.toString());
// Use Jsoup on response to parse it if it makes your work easier.
} catch (Exception e) {
e.printStackTrace();
}
It would be useful if someone could share their solution for the former approach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.