在不使用任何外部库的情况下,将网站的HTML内容提取为字符串的最简单方法是什么?
发布于 2008-08-28 01:21:01
我目前使用的是:
String content = null;
URLConnection connection = null;
try {
connection = new URL("http://www.google.com").openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
scanner.close();
}catch ( Exception ex ) {
ex.printStackTrace();
}
System.out.println(content);
但不确定是否有更好的方法。
发布于 2008-08-29 05:11:11
这对我来说效果很好:
URL url = new URL(theURL);
InputStream is = url.openStream();
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while ((ptr = is.read()) != -1) {
buffer.append((char)ptr);
}
不确定所提供的其他解决方案是否更有效。
发布于 2008-08-28 01:31:53
我刚离开了this post in your other thread,不过你上面的可能也能用。我不认为其中任何一个会比另一个更容易。只需在代码顶部使用import org.apache.commons.HttpClient
即可访问Apache包。
编辑:忘记链接;)
https://stackoverflow.com/questions/31462
复制相似问题