Spring RestTemplate使用cookie重定向 [英] Spring RestTemplate follow redirect with cookie
问题描述
最近我遇到了一个问题,我需要对远程服务执行 GET
请求(使用我假设的简单servlet),RestTemplate返回重定向太多了!
。
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!
.
经过一番调查,似乎第一次向指定的远程服务发出请求,实际上只是一个302-使用一些 Set-Cookie
标题重定向(自身)。如果我使用的是普通浏览器,它会确认标题,正确设置Cookie,并按照重定向进行正常的200响应。
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.
什么我发现RestTemplate不接受 Set-Cookie
标题,因此重定向会一遍又一遍地进行。
What I've found is that RestTemplate doesn't accept the Set-Cookie
header, so the redirect gets made over and over again.
有没有办法让RestTemplate只为当前请求确认 Set-Cookie
标题?我最好不要让它保持状态,因为RestTemplate也用于系统的其他部分。
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.
问候
推荐答案
Spring默认请求工厂( SimpleClientHttpRequestFactory
)不处理cookie。将其替换为具有Apache HttpClient
的请求工厂,该工厂可以使用cookie:
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);
这篇关于Spring RestTemplate使用cookie重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!