복붙노트

[SPRING] Spring restTemplate을 사용하여 302 리디렉션을 따릅니 까?

SPRING

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 호가 자동으로 따라 가게 될 것이라는 인상을 받았다. 나는이 가정에서 틀린가? 이제이 위치를 선택하고 다시 요청해야합니까?

해결법

  1. ==============================

    1.기본 ClientHttpRequestFactory 구현 - SimpleClientHttpRequestFactory -를 사용하면 기본 동작은 위치 요청 헤더 (상태 코드 3xx가있는 응답)를 따르는 것입니다. 단, 초기 요청이 GET 요청 인 경우에만 수행하십시오.

    기본 ClientHttpRequestFactory 구현 - SimpleClientHttpRequestFactory -를 사용하면 기본 동작은 위치 요청 헤더 (상태 코드 3xx가있는 응답)를 따르는 것입니다. 단, 초기 요청이 GET 요청 인 경우에만 수행하십시오.

    이 클래스에서 세부 정보를 찾을 수 있습니다. 다음 메소드를 검색하십시오.

    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
    
        ...
    
        if ("GET".equals(httpMethod)) {
            connection.setInstanceFollowRedirects(true);
        }
    

    다음은 HttpURLConnection.setInstanceFollowRedirects 메서드의 관련 문서 주석입니다.

  2. ==============================

    2.CommonsClientHttpRequestFactory (HttpClient v3 아래 사용)를 사용하는 경우 postProcessCommonsHttpMethod 메서드를 재정의하고 리디렉션을 따르도록 설정할 수 있습니다.

    CommonsClientHttpRequestFactory (HttpClient v3 아래 사용)를 사용하는 경우 postProcessCommonsHttpMethod 메서드를 재정의하고 리디렉션을 따르도록 설정할 수 있습니다.

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

    그런 다음 (미리 정의 된 HttpClient 인스턴스를 사용하여 선택적으로) 다음과 같이 사용할 수 있으며 요청은 응답으로 위치 헤더를 따릅니다.

    RestTemplate restTemplate = new RestTemplate(
          new FollowRedirectsCommonsClientHttpRequestFactory());
    
  3. from https://stackoverflow.com/questions/29418583/follow-302-redirect-using-spring-resttemplate by cc-by-sa and MIT license