I am posting information to a web service using RestTemplate.postForObject. Besides the result string I need the information in the response header. Is there any way to get this?
RestTemplate template = new RestTemplate(); String result = template.postForObject(url, request, String.class);
3.2. Now we can use the simpler getForObject() method to get the list of employees: EmployeeList response = restTemplate. getForObject( "http://localhost:8080/employees", EmployeeList. class); List<Employee> employees = response.
I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders . (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.
Note: RestTemplate getForEntity () method does not support request headers. Please use exchange () method if headers are necessary. To produce an error scenario, let’s do not add the mandatory header in the request entity.
The response body is a stream and if you read it in your interceptor it won’t be available for RestTemplate to deserialize it into your object model. In other words, when you call restTemplate.get… you’ll always get back empty objects (even as you see the object in your response.
In this, Spring Boot RestTemplate GET request example, learn to use RestTemplate to invoke REST GET API verify api response status code and response entity body. To create the rest apis, use the sourcecode provided in spring boot 2 rest api example. 1. Maven dependencies Make sure to have spring-boot-starter-web dependency in the project.
Note: Spring docs recommend to use the non-blocking, reactive WebClient which offers efficient support for both sync, async and streaming scenarios. RestTemplate will be deprecated in the future versions. 1. Spring RestTemplate class Accessing the REST apis inside a Spring application revolves around the use of the Spring RestTemplate class.
Ok, I finally figured it out. The exchange method is exactly what i need. It returns an HttpEntity which contains the full headers.
RestTemplate template = new RestTemplate(); HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class); String resultString = response.getBody(); HttpHeaders headers = response.getHeaders();
Best thing to do whould be to use the execute method and pass in a ResponseExtractor which will have access to the headers.
private static class StringFromHeadersExtractor implements ResponseExtractor<String> { public String extractData(ClientHttpResponse response) throws { return doSomthingWithHeader(response.getHeaders()); } }
Another option (less clean) is to extend RestTemplate and override the call to doExecute
and add any special header handling logic there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With