目前我使用HttpURLConnection加载远程网页和呈现给我的客户端(使用InputStream到HttpResponse的outputStream传输),它正确加载HTML,但跳过图像,如何解决它?使HttpURLConnection加载网页与图像
谢谢
目前我使用HttpURLConnection加载远程网页和呈现给我的客户端(使用InputStream到HttpResponse的outputStream传输),它正确加载HTML,但跳过图像,如何解决它?使HttpURLConnection加载网页与图像
谢谢
您需要以这种方式操纵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.
}
是的,这真的很有意义......这是奇怪的是,没有工具可以使这个开箱 – Fagoter 2011-06-08 20:15:38