RestTemplate.exchange() DELETE 删除请求体

我在使用下面的方法时遇到了一个奇怪的问题。

@Override
public String deleteToEe(String body) {     
    logger.debug("Request body");
    logger.debug(body);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    headers.add("partner", "test");
    headers.add("api_key", "certxxxx");
    HttpEntity<String> request = new HttpEntity<String>(body, headers);
    ResponseEntity<String> result = null;
    try {
        result = restTemplate.exchange(targetUrl, HttpMethod.DELETE, request, String.class);
    } catch (RestClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result.getBody();
}

当我通过 Postman 访问控制器请求映射来触发此方法时,它可以工作。但是当测试人员通过他们的集成测试触发这个方法时,或者当我使用 curl 触发这个方法时

curl -X DELETE -H "Accept: application/json" -H "Content-type: application/json" -d "{"userName": "21", "courseId": "104882_bfaculty3_1024", "isbn": "9780323055", "schoolUserId": "1234" }" http://localhost:8080//api/provision

我在代码中此时出现空指针异常

result = restTemplate.exchange(targetUrl, HttpMethod.DELETE, request, String.class);

我已经为代码设置了断点,看起来我们有一个请求正文,但由于某种原因,它在 restTemplate.exchange() 调用中被删除了。以前有人见过这样的东西吗?

stack overflow RestTemplate.exchange() DELETE dropping request body
原文答案

答案:

作者头像

You should not have any body in the request when using HTTP DELETE method. Many frameworks discourage using it or warn you that the body may be dropped. The reason is that you want to DELETE some resource identified by your URI thus no body should be required.

It sounds like this may be your case. It would also explain why some tools do send the body and why others doesn't.

I would strongly recommend you to re-design your API to something similar to

DELETE http://localhost:8080/api/provision/{id}

or different URI dependent on how your data (resources) are designed