java - 我在处理 REST Assured API POST 请求时遇到问题

标签 java spring rest spring-boot

当我在 Eclipse 中的普通 java 项目中的 java 文件中执行以下代码时,它运行成功:

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);

执行成功后会在指定表中添加一条新记录;(customDependants(IN),此处的表)。

然而,当我在 Spring Boot 项目中运行相同的内容时,出现错误:

java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <400>.

仅供引用:我尝试使用其他请求参数代替 contentType("application/json"),例如:headers("Content-Type", ContentType.JSON)

错误日志:

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 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 代码中出现此错误:

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);
                }
            }
        }
    }

当我运行时,它会一直运行到被 # 包围的 LOG,然后当 API 被调用时,响应是 Malformed XML。 gson.toJson(employeeDependentDTO) 的值为 {"customName":"abcd","customGender":"male","customDateofBirth":"2010-12-08","customRelationship":"child"}

此外,这里我将内容类型设置为 JSON 而不是 XML,甚至负载也是 JSON 格式,适用于 postman 和非 spring boot 项目。

仅供引用:所有获取请求都在 Spring Boot 应用程序中完美运行,当我尝试使用帖子访问 API 时,只会收到上述错误,而如果我在非 Spring 应用程序中执行相同的操作,则一切正常。在 postman 中同样工作正常。

请帮助我解释为什么它无法在 Spring Boot 应用程序中执行。

最佳答案

我在这里使用了另一种解决方案,在 java 中使用 HttpURLConnection,它工作得很好,下面是替换上面放心代码的代码:

              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();
                }

如果有人可以分享他们对前一种方法的解决方案,那将会很有用。

关于java - 我在处理 REST Assured API POST 请求时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539119/

相关文章:

rest - SOA 最常用的技术是什么?

web-services - RESTful Web 服务中的身份验证

java - 无法使用 Set 删除重复的对号

java - 连接到 LDAP 服务器,无需硬编码凭据

java - 将 Map<T> 转换为派生类

java - 如何在父类(super class)中重用@Autowired bean?

java - spring url 与当前本地日期

r - 在 R 中关注使用 twitter Rest Api 的人

java - spring中嵌套配置属性的前缀

java - 创建自定义注释以验证 header 中的 userToken