我希望能够获取网页的html并将其保存到String
,这样我就可以对其进行一些处理。另外,我如何处理各种类型的压缩。
我该如何使用Java来做这件事呢?
发布于 2008-10-26 21:09:39
下面是一些使用Java的URL类测试过的代码。不过,我建议在处理异常或将它们向上传递到调用堆栈方面做得比我在这里做得更好。
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
发布于 2010-04-06 13:17:00
Bill的回答非常好,但您可能希望对请求执行一些操作,如压缩或用户代理。下面的代码展示了如何对请求进行各种类型的压缩。
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;
// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
} else {
inStr = conn.getInputStream();
}
要同时设置用户代理,请添加以下代码:
conn.setRequestProperty ( "User-agent", "my agent name");
发布于 2014-05-30 18:30:16
上面提到的所有方法都不会下载在浏览器中出现的网页文本。现在很多数据都是通过html页面中的脚本加载到浏览器中的。上面提到的技术都不支持脚本,它们只下载html文本。HTMLUNIT支持javascripts。因此,如果你想下载在浏览器中显示的网页文本,那么你应该使用HTMLUNIT。
https://stackoverflow.com/questions/238547
复制相似问题