Somebody else might be confused, so here is a more detailed answer:
private ResponseEntity<List<ResponseDto>> sendRequest(List<RequestDto> requestList) {
String URL = "http://localhost:8080/endpoint"; // my endpoint
HttpHeaders headers = new HttpHeaders(); //here you set any headers you need
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<List<RequestDto>> request = new HttpEntity<>(requestList, headers); // create the entity object you need to pass as a request object. In my case, it's an array of objects
return restTemplate.exchange(URL, HttpMethod.POST, request, new ParameterizedTypeReference<List<ResponseDto>>() {
});
}
In the last line, as the restTemplate.postForEntity(...)
does not allow for Collections of elements as a response, we use the exchange(...)
method. Its parameters are:
URL
-> String object, the endpoint for the request
method
-> HttpMethod object (GET, POST, PUT, PATCH etc)
requestEntity
-> HttpEntity object, the one that is being created above (mine was called request
). It has both the headers for the request and the payload/body
responseType
-> it's the 4th argument, a ParameterizedTypeReference
abstract class. This one is used when the returned type is a Collection
, not a simple array or just an object. When the endpoint returns a collection of objects, you cannot do something like Collection<ResponseDto>.class
because it's impossible
Another workaround, if you don't need the ResponseEntity
object itself, but only the result object, you can do something like
ResponseEntity<ResponseDto[]> responseEntity = restTemplate.postForEntity(URL, request, ResponseDto[].class); // convert the response body to a simple array, not Collection
return Arrays.asList(responseEntity.getBody()); // convert to Collection if needed