Spring RestTemplate should be redirected with a cookie

I recently ran into a problem when I needed to make a GET request to a remote service (using the simple servlet that I assume), and RestTemplate returned Too many redirects! .

After some investigation, it seems that the first request made to the specified remote service is actually a 302 redirect (for itself) with some Set-Cookie headers. If I used a "normal" browser, it would confirm the header, set the cookies correctly and redirect where it should correspond to the normal 200 response.

I found that RestTemplate does not accept the Set-Cookie header, so the redirect is done over and over again.

Is there a way to get RestTemplate to accept the Set-Cookie header for the current request only? I prefer that it does not support state, since RestTemplate is also used from other parts of the system.

Hi

+6
source share
3 answers

Spring factory default request ( SimpleClientHttpRequestFactory ) does not process cookies. Replace it with a factory request with Apache HttpClient , which can use cookies:

 import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; CloseableHttpClient httpClient = HttpClientBuilder .create() .build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); 
+6
source

I solved this problem differently than Michal Fox. (Before he answered that)

One way to solve it is to implement a local stream cookiemanager and set it as the system default. This causes RestTemplate to store cookies with cookiemanager and release cookiemanager after the requesting stream is dead.

Hi

+1
source

Better use the latest version of httpclient. By default, the spring rest pattern does not allow you to set a header.

0
source

All Articles