RestTemplate client with cookies
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
I've solved the problem by creating an interceptor which stores a cookie and puts it in next requests.
public class StatefulRestTemplateInterceptor implements ClientHttpRequestInterceptor {
private String cookie;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
if (cookie != null) {
request.getHeaders().add(HttpHeaders.COOKIE, cookie);
}
ClientHttpResponse response = execution.execute(request, body);
if (cookie == null) {
cookie = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE);
}
return response;
}
}
Set the interceptor for your RestTemplate:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder templateBuilder) {
return templateBuilder
.requestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()))
.interceptors(new StatefulRestTemplateInterceptor())
.build();
}