2011-06-08 46 views
1

目前我使用HttpURLConnection加載遠程網頁和呈現給我的客戶端(使用InputStream到HttpResponse的outputStream傳輸),它正確加載HTML,但跳過圖像,如何解決它?使HttpURLConnection加載網頁與圖像

謝謝

回答

3

您需要以這種方式操縱HTML,以便Intranet域上的所有資源URL都被代理。例如。所有HTML

<base href="http://intranet.com/" /> 
<script src="http://intranet.com/script.js"></script> 
<link href="http://intranet.com/style.css" /> 
<img src="http://intranet.com/image.png" /> 
<a href="http://intranet.com/page.html">link</a> 

以下資源引用的,應在HTML,讓他們通過你的代理servlet來代替,例如可以改變這種方式

<base href="http://example.com/proxy/" /> 
<script src="http://example.com/proxy/script.js"></script> 
<link href="http://example.com/proxy/style.css" /> 
<img src="http://example.com/proxy/image.png" /> 
<a href="http://example.com/proxy/page.html">link</a> 

一個HTML解析器像Jsoup在這個非常有幫助。您可以在您的代理servlet中執行以下操作,我假設它將映射到/proxy/*的URL模式。

String intranetURL = "http://intranet.com"; 
String internetURL = "http://example.com/proxy"; 

if (request.getRequestURI().endsWith(".html")) { // A HTML page is requested. 
    Document document = Jsoup.connect(intranetURL + request.getPathInfo()).get(); 

    for (Element element : document.select("[href]")) { 
     element.attr("href", element.absUrl("href").replaceFirst(intranetURL, internetURL)); 
    } 

    for (Element element : document.select("[src]")) { 
     element.attr("src", element.absUrl("src").replaceFirst(intranetURL, internetURL)); 
    } 

    response.setContentType("text/html;charset=UTF-8"); 
    response.setCharacterEncoding("UTF-8"); 
    resposne.getWriter().write(document.html()); 
} 
else { // Other resources like images, etc. 
    URLConnection connection = new URL(intranetURL + request.getPathInfo()).openConnection(); 

    for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { 
     for (String value : header.getValue()) { 
      response.addHeader(header.getKey(), value); 
     } 
    } 

    InputStream input = connection.getInputStream(); 
    OutputStream output = response.getOutputStream(); 
    // Now just copy input to output. 
} 
+0

是的,這真的很有意義......這是奇怪的是,沒有工具可以使這個開箱 – Fagoter 2011-06-08 20:15:38

1

您必須爲每個圖像提出一個單獨的請求。這就是瀏覽器所做的。

+0

Bozho,這不會幫助他(w /圖片我的意思)...因爲圖像源也必須重定向。 – bestsss 2011-06-08 15:11:11

+0

我認爲HtmlUnit可以從網頁中提取圖像網址,並讓您爲每個網頁提出新的請求。 – Bozho 2011-06-08 15:36:52

+0

這很明顯,但據我瞭解意圖,OP希望客戶能夠請求他們。爲了做到這一點,他們必須解析html併爲這些圖像提出專門的請求。這不是一件容易的事。 – bestsss 2011-06-08 16:21:07