0

我必須獲取重定向URL以查看是否可以下載最終頁面。 HttpHead用於獲取最終目標網址(請參閱下面的代碼)。使用Apache HttpHead進行URI編碼在retreiving重定向網址前

HttpClient client = HttpClientBuilder.create().build(); 

HttpHead httpHead = new HttpHead("http://bit.ly/1DfSWSs"); 

HttpClientContext context = HttpClientContext.create(); 
client.execute(httpHead, context); 
List<URI> redirectLocations = context.getRedirectLocations(); 
if (redirectLocations != null && !redirectLocations.isEmpty()) { 
    for (URI redirectURI : redirectLocations) { 
     //TODO print all 
    } 
} 

問題是代碼中的URL示例。重定向網址中包含空格,因此無法創建URI。

有沒有什麼辦法可以在調用getRedirectLocations方法之前對URI對象進行編碼?

回答

1

自定義重定向策略是你的朋友

CloseableHttpClient client = HttpClientBuilder.create() 
     .setRedirectStrategy(new DefaultRedirectStrategy() { 
      @Override 
      protected URI createLocationURI(final String location) throws ProtocolException { 
       // One can try to rewrite malformed redirect locations 
       //at this point 
       return super.createLocationURI(location); 
      } 
     }) 
     .build(); 
+0

謝謝,我會嘗試它的時候了。 – EnterSB 2014-10-17 09:47:20

+0

它很好用。再次感謝。 – EnterSB 2014-10-17 09:55:01