2011-06-08 42 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