Spring RestTemplate遵循cookie重定向

Rob*_*son 8 java rest integration spring resttemplate

最近我遇到了一个问题,我需要向GET远程服务请求(使用我假设的简单servlet),并返回RestTemplate Too many redirects!.

经过一番调查后,似乎对指定的远程服务发出的第一个请求实际上只是一个带有一些Set-Cookie头文件的302重定向(自身).如果我使用的是"普通"浏览器,它会确认标题,正确设置Cookie,并按照重定向进行正常的200响应.

我发现RestTemplate不接受Set-Cookie标题,所以重定向一遍又一遍.

有没有办法让RestTemplate确认Set-Cookie标题,仅针对当前请求?我最好不要让它保持状态,因为RestTemplate也是从系统的其他部分使用的.

问候

Mic*_*ksa 8

Spring默认请求factory(SimpleClientHttpRequestFactory)不处理cookie.用Apache的请求工厂替换它,它具有HttpClientcookie功能:

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);
Run Code Online (Sandbox Code Playgroud)