Spring RestTemplate follow redirect with cookie

99封情书 提交于 2019-12-04 03:31:16

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);

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!