如何从RestTemplate获取重定向的URL?

时间:2016-08-04 18:16:56

标签: java spring url redirect resttemplate

我想用http GET调用RestTemplate并检索状态代码和重定向的url(如果有的话)。

如何实现?

3 个答案:

答案 0 :(得分:1)

  1. 使用自定义HttpClient创建Apache RedirectStrategy,您可以在重定向时拦截中间响应。
  2. 将默认请求工厂替换为HttpComponentsClientHttpRequestFactory和新的Apache HttpClient
  3. 有关详细信息,请查看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);
    .......
    

答案 1 :(得分:1)

var responseEntity = restTemplate.exchange("someurl", HttpMethod.GET, null, Object.class);
HttpHeaders headers = responseEntity.getHeaders();
URI location = headers.getLocation();
location.toString();

答案 2 :(得分:0)

使用Spring并覆盖SimpleClientHttpRequestFactory中的prepareConnection()...

RedirectMatch 301 "^/$" "/FormTest/register/"
RedirectMatch 301 "^/index\.html$" "/FormTest/register/"
RedirectMatch 301 "^/index\.php$" "/FormTest/register/"