13

Recently I ran into a problem where I needed to do a GET 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 Set-Cookie 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 Set-Cookie header, so the redirect gets made over and over again.

Is there any way to make RestTemplate acknowledge the Set-Cookie 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.

Regards

Robin Jonsson
  • 2,761
  • 3
  • 22
  • 42
  • Is [this](http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate) what you want to do? Also [this one](http://stackoverflow.com/questions/22853321/resttemplate-client-with-cookies) ? – ha9u63a7 May 04 '16 at 10:14
  • @ha9u63ar Botht links adds a cookie to the request header. I preferably don't want to make 2 separate requests. (1 for first stopping at the redirect, sniffing the "Set-Cookie" header, adding it to the second request and executing that one) I want RestTemplate to follow the redirect (it actually does this already) while also acknowledging the "Set-Cookie" header. – Robin Jonsson May 04 '16 at 10:58

3 Answers3

12

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
    .create()
    .build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
Michal Foksa
  • 11,225
  • 9
  • 50
  • 68
1

I did solve this problem in another way than Michal Foksa did. (Before he answered this)

One way to solve it is to implement a thread-local cookiemanager, and set it as the system default. This will make the RestTemplate store cookies with the cookiemanager, and release the cookiemanager once the requesting thread is dead.

Regards

Robin Jonsson
  • 2,761
  • 3
  • 22
  • 42
-2

Better to use the latest version of httpclient. By default the spring rest template will not allow to set the header.

Raju
  • 143
  • 5