使用Spring restTemplate跟随302重定向?

tec*_*don 17 java redirect spring resttemplate

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

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

fat*_*ddy 19

使用默认ClientHttpRequestFactory实现 - 即SimpleClientHttpRequestFactory - 默认行为是遵循位置标头的URL(对于具有状态代码的响应3xx) - 但仅当初始请求是GET请求时.

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

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

    ...

    if ("GET".equals(httpMethod)) {
        connection.setInstanceFollowRedirects(true);
    }
Run Code Online (Sandbox Code Playgroud)

这里方法的相关文档评论HttpURLConnection.setInstanceFollowRedirects:

设置此{@code HttpURLConnection}实例是否应自动遵循HTTP重定向(响应代码为3xx的请求).

默认值来自followRedirects,默认为true.

  • 我做了`new RestTemplate(new SimpleClientHttpRequestFactory(){protected void prepareConnection(HttpURLConnection connection,String httpMethod)抛出IOException {super.prepareConnection(connection,httpMethod); connection.setInstanceFollowRedirects(false);}});`来禁用重定向 (11认同)

Vla*_*tev 8

您是否尝试从一种协议重定向到另一种协议,例如从 http 重定向到 https 或反之亦然?如果是这样,自动重定向将不起作用。请参阅此评论:URLConnection 不遵循重定向

经过Java Networking工程师的讨论,我们认为我们不应该自动遵循从一种协议到另一种协议的重定向,例如从http到https,反之亦然,这样做可能会产生严重的安全后果

来自https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4620571

否则,如果您调试RestTemplate代码,您将看到默认情况下HttpURLConnection使用getInstanceFollowRedirects() == true.