Robin Jonsson Robin Jonsson - 5 months ago 299x
Java Question

Spring RestTemplate follow redirect with cookie

Recently I ran into a problem where I needed to do a

request to a remote service (Using a simple servlet i presume), and RestTemplate returned
Too many redirects!

After some investigation, it seems like the first request made to the specified remote service, is actually just a 302-redirect (to itself) with some
headers. If I were using a "normal" browser, it would acknowledge the header, set the cookies correctly, and follow the redirect where it should meet a normal 200 response.

What I've found is that RestTemplate doesn't accept the
header, so the redirect gets made over and over again.

Is there any way to make RestTemplate acknowledge the
header, for the current request only? I preferably don't want it to hold state, as the RestTemplate is used from other parts of the system as well.



Spring default request factory (SimpleClientHttpRequestFactory) does not handle cookies. Replace it with a request factory with Apache HttpClient which is capable of 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
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);