簡體   English   中英

如何從RestTemplate獲取重定向的URL?

[英]How to get redirected url from RestTemplate?

我想用http GET調用RestTemplate並檢索狀態代碼和重定向的url(如果有的話)。

如何實現呢?

  1. 使用自定義RedirectStrategy創建Apache HttpClient ,您可以在其中發生重定向時攔截中間響應。
  2. 將默認請求工廠替換為HttpComponentsClientHttpRequestFactory和新的Apache HttpClient

請查看org.apache.http.client.RedirectStrategy了解更多信息。 或如以下示例中那樣重用DefaultRedirectStrategy

CloseableHttpClient httpClient = HttpClientBuilder
        .create()
        .setRedirectStrategy( new DefaultRedirectStrategy() {

            @Override
            public boolean isRedirected(HttpRequest request, HttpResponse response,
                    HttpContext context) throws ProtocolException {

                System.out.println(response);

                // If redirect intercept intermediate response.
                if (super.isRedirected(request, response, context)){
                    int statusCode  = response.getStatusLine().getStatusCode();
                    String redirectURL = response.getFirstHeader("Location").getValue();
                    System.out.println("redirectURL: " + redirectURL);
                    return true;
                }
                return false;
            }
        })
        .build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
.......
var responseEntity = restTemplate.exchange("someurl", HttpMethod.GET, null, Object.class);
HttpHeaders headers = responseEntity.getHeaders();
URI location = headers.getLocation();
location.toString();

使用Spring並覆蓋SimpleClientHttpRequestFactory中的prepareConnection()...

RestTemplate restTemplate = new RestTemplate( new SimpleClientHttpRequestFactory(){
    @Override
    protected void prepareConnection( HttpURLConnection connection, String httpMethod ) {
        connection.setInstanceFollowRedirects(false);
    }
} );

ResponseEntity<Object> response = restTemplate.exchange( "url", HttpMethod.GET, null, Object.class );
int statusCode = response.getStatusCodeValue();
String location = response.getHeaders().getLocation() == null ? "" : response.getHeaders().getLocation().toString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM