Follow 302 redirect using Spring restTemplate?

前端 未结 3 791
庸人自扰
庸人自扰 2020-12-06 16:19
  RestTemplate restTemplate = new RestTemplate();

  final MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
  final L         


        
3条回答
  •  既然无缘
    2020-12-06 16:35

    When using the CommonsClientHttpRequestFactory (which uses HttpClient v3 underneath) you can override the postProcessCommonsHttpMethod method and set to follow redirects.

    public class FollowRedirectsCommonsClientHttpRequestFactory extends CommonsClientHttpRequestFactory {
    
      @Override
      protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) {
        httpMethod.setFollowRedirects(true);
      }
    }
    

    You can then use it like this (with optional, possibly preconfigured, HttpClient instance) and requests will follow the location headers in response:

    RestTemplate restTemplate = new RestTemplate(
          new FollowRedirectsCommonsClientHttpRequestFactory());
    

提交回复
热议问题