gpt4 book ai didi

java - Spring RestTemplate 遵循带有 cookie 的重定向

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:41 29 4
gpt4 key购买 nike

最近我遇到了一个问题,我需要对远程服务执行一个GET 请求(我想是使用一个简单的 servlet),而 RestTemplate 返回了重定向太多!.

经过一些调查,似乎对指定远程服务的第一个请求实际上只是一个带有一些 Set-Cookie header 的 302 重定向(到自身)。如果我使用的是“普通”浏览器,它会确认 header ,正确设置 cookie,并在应该满足正常 200 响应的地方遵循重定向。

我发现 RestTemplate 不接受 Set-Cookie header ,因此会一遍又一遍地进行重定向。

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

问候

最佳答案

Spring 默认请求工厂 (SimpleClientHttpRequestFactory) 不处理 cookie。将其替换为具有 cookie 能力的 Apache HttpClient 的请求工厂:

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

关于java - Spring RestTemplate 遵循带有 cookie 的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37024709/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com