gpt4 book ai didi

java - 使用 Spring restTemplate 遵循 302 重定向?

转载 作者:IT老高 更新时间:2023-10-28 13:52:48 27 4
gpt4 key购买 nike

  RestTemplate restTemplate = new RestTemplate();

final MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
final List<MediaType> supportedMediaTypes = new LinkedList<MediaType>(converter.getSupportedMediaTypes());
supportedMediaTypes.add(MediaType.ALL);
converter.setSupportedMediaTypes(supportedMediaTypes);
restTemplate.getMessageConverters().add(converter);


ResponseEntity<MyDTO[]> response = restTemplate.getForEntity(urlBase, MyDTO[].class);

HttpHeaders headers = response.getHeaders();
URI location = headers.getLocation(); // Has my redirect URI

response.getBody(); //Always null

我的印象是会自动遵循 302。我在这个假设中不正确吗?我现在需要选择这个位置并重新申请吗?

最佳答案

使用默认的 ClientHttpRequestFactory 实现 - 即 SimpleClientHttpRequestFactory - 默认行为是跟随位置 header 的 URL(对于具有状态代码 3xx 的响应) - 但前提是初始请求是 GET 请求。

可以在这个类中找到详细信息-搜索以下方法:

protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {

...

if ("GET".equals(httpMethod)) {
connection.setInstanceFollowRedirects(true);
}

这里是HttpURLConnection.setInstanceFollowRedirects方法的相关文档注释:

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this {@code HttpURLConnection} instance.

The default value comes from followRedirects, which defaults to true.

关于java - 使用 Spring restTemplate 遵循 302 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29418583/

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