使用Spring restTemplate跟随302重定向?

  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 – 默认行为是遵循位置标头的URL(对于状态代码为3xx的响应) – 但仅限于初始请求是GETrequest.

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

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.

上一篇:Spring RestTemplate详解(转载)


下一篇:java – 带有cookie的RestTemplate客户端