javaspringhttpentity

Spring - generic method for getting body from ResponseEntity using HttpEntity


In my code I am very often using HttpEntity alongside ResponseEntity in a following way:

HttpEntity<?> request = new HttpEntity<String>(myObject, headers);

ResponseEntity<String> response = restTemplate.exchange("someurl", HttpMethod.POST, request, String.class);

and then

response.getBody()

I repeat this code all the time, I was wondering if it is possible to create a generic method that would allow me to get response.body() when I supply it with object I want to send, an url, and a HttpMethod type. The response body most of the time will be a string, but can be an object.


Solution

  • You can use below code, here the response body and request body are made generic:

    public <T, R> T yourMethodName(R requestBody, 
                                   MultiValueMap<String, String> headers, 
                                   String url, 
                                   HttpMethod type, 
                                   Class<T> clazz) {
        HttpEntity<?> request = new HttpEntity<String>(requestBody, headers);
       //You have to create restemplate Obj somewhere
        ResponseEntity<T> response = restTemplate.exchange(url, type, request, clazz);
        return response.getBody();
    }