开发者

How do I read the response header from RestTemplate?

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 tem开发者_StackOverflowplate = new RestTemplate();
String result = template.postForObject(url, request, String.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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜