简体   繁体   中英

RestTemplate.exchange() DELETE dropping request body

I'm experiencing a strange problem with the method below.

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

When I trigger this method through hitting the controller request mapping through Postman, it works. But when testers triggers this method through their integration tests, or when I trigger this method using 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

I get a null pointer exception at this point in the code

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

I've breakpointed the code and looks like we have a request body but for some reason it' being dropped at the restTemplate.exchange() call. Anyone seen something like this before?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM