47

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);
Eric Milas
  • 1,807
  • 2
  • 18
  • 29

4 Answers4

72

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();
Eric Milas
  • 1,807
  • 2
  • 18
  • 29
  • 3
    If you need the status: ResponseEntity> response = template.exchange(...); response.getStatusCode(); – olafure Nov 20 '13 at 13:05
  • 5
    You could also have called 'postForEntity', which is a slightly simpler method. – ayahuasca Apr 02 '14 at 13:14
  • The only problem I see with this is that template.exchange method uses restTemplate.getMessageConverters() in order to create the HttpMessageConverterExtractor for you. This may or may not be what you want. For most cases you WILL want to use this and set up your message converters in spring-mvc-servlet.xml. – gaoagong Sep 17 '14 at 17:50
9

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.

Andrew White
  • 52,720
  • 19
  • 113
  • 137
  • +1, but probably better to extend the existing `HttpMessageConverterExtractor` and override, rather than write a whole new one. – skaffman May 15 '11 at 08:31
  • execute wants a RequestCallback as one of its parameters. I cannot find an example anywhere of how to implement it to contain the request body. postForObject just takes a HttpEntity, any ideas? – Eric Milas May 15 '11 at 21:22
3
  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();
Deepak
  • 741
  • 1
  • 5
  • 13
1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216