How do I read the response header from RestTemplate?

后端 未结 4 832
醉梦人生
醉梦人生 2020-12-05 06:34

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 ge

相关标签:
4条回答
  • 2020-12-05 07:12

    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.

    0 讨论(0)
  • 2020-12-05 07:12
      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();
    
    0 讨论(0)
  • 2020-12-05 07:26

    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();
    
    0 讨论(0)
  • 2020-12-05 07:29

    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 讨论(0)
提交回复
热议问题