2017-09-06 119 views
0

概述:问题与RestTemplate重定向

下面的代码负责调用外部REST服务。外部服务重定向到一个页面。

restTemplate.exchange(
       "http://localhost:8080/<endpoint address>", 
       GET, 
       new HttpEntity<String>(headers), 
       String.class); 

问题:

响应背上这是错误的纯HTML文本。 预期的是重定向到外部服务已被重定向到的页面。

*有什么办法可以处理吗?

+0

它取决于底层http库,你知道你在使用哪个? – Taylor

+0

感谢您的及时回应。 这是spring-web-4.3.6.RELEASE – saeedj

+0

这不是http库。这可能是apache http或okhttp或者其他的。找出这是什么,并看看配置。它比春天低。 – Taylor

回答

0

我找到了解决方案,通过使用HttpURLConnection的而不是RestTemplate

HttpURLConnection con = getHttpURLConnection(); 

    try { 
     con.setInstanceFollowRedirects(true); 
     con.setRequestProperty(requestHeaderName, requestHeaderValue); 
     HttpURLConnection.setFollowRedirects(true); 
     con.getResponseCode(); 

     verifyResponseCode(con); 

     String redirectPath = con.getURL().toString(); 
     return new RedirectView(redirectPath); 

    } catch (RestClientException e) { 
     log.error(e.getMessage(), e); 
     throw e; 
    } 

而在getHttpURLConnection:

HttpURLConnection getHttpURLConnection() throws Exception { 
    URL securedUrl = new URL("URL"); 
    return (HttpURLConnection) securedUrl.openConnection(); 
} 

现在它为我工作。 con.getURL()返回来自外部服务的重定向URL,现在我可以访问它。