RestTemplate client with cookies

Tom picture Tom · Apr 4, 2014 · Viewed 58.7k times · Source

I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the server. In the response to the Connect POST there are cookies set by the server which need to be present in the subsequent POST for publishing the file. I'm currently using Spring RestTemplate in my client.

My question is how do I access the cookies in the response to forward back to the server with the subsequent POST? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity to access them.

Answer

Koitoer picture Koitoer · Apr 4, 2014

RestTemplate has a method in which you can define Interface ResponseExtractor<T>, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity and added again.

 .add("Cookie", "SERVERID=c52");

Try something like this.

String cookieHeader = null;

new ResponseExtractor<T>(){
      T extractData(ClientHttpResponse response) {
        response.getHeaders();
      }
}

Then

  HttpHeaders headers = new HttpHeaders();
  headers.add("Cookie", cookieHeader );

  ResponseEntity<byte[]> response = restTemplate.exchange("http://example.com/file/123",
      GET,
      new HttpEntity<String>(headers),
      byte[].class);

Also read this post