2017-09-06 277 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,現在我可以訪問它。