Question

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);
Was it helpful?

Solution

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

OTHER TIPS

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.

I don't know if this is the recommended method, but it looks like you could extract information from the response headers if you configure the template to use a custom HttpMessageConverter.

  HttpEntity<?> entity = new HttpEntity<>( postObject, headers ); // for request
    HttpEntity<String> response = template.exchange(url, HttpMethod.POST, entity, String.class);
    String result= response.getBody();
    HttpHeaders headers = response.getHeaders();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top