问题
我希望能够获取网页的html并保存到aString
,所以我可以对它进行一些处理。另外,我如何处理各种类型的压缩。
我将如何使用Java进行此操作?
#1 热门回答(158 赞)
我会使用一个体面的HTML解析器,如Jsoup。然后就像这样简单:
String html = Jsoup.connect("http://stackoverflow.com").get().html();
它完全透明地处理GZIP和分块响应以及字符编码。它提供了更多的优势,比如像jQuery那样的CSS选择器的HTMLtraversing和manipulation。你只需抓住它作为Document
,而不是aString
。
Document document = Jsoup.connect("http://google.com").get();
你真的需要运行基本的String方法,甚至是HTML上的正则表达式来处理它。
也可以看看:
- Java中领先的HTML解析器的优缺点是什么?
#2 热门回答(99 赞)
这是使用Java的URLclass测试的一些代码。不过,我建议做一个比处理异常或将它们传递给调用堆栈更好的工作。
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
}
}
}
#3 热门回答(22 赞)
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();
}
要同时设置user-agent,请添加以下代码:
conn.setRequestProperty ( "User-agent", "my agent name");