在我的应用程序中,我从一个公共(public) URL 发出请求,然后打开网页的源代码,最后,我从源代码中提取我想要的信息。整个过程我没有遇到任何问题。但是,加载我想要的信息需要很长时间。还有其他有效的方法吗?
public class GetMethodEx {
public String getInternetData(String currentUrl) throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI(currentUrl);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
最佳答案
使用 StringBuffer 下载大文本确实效率不高,因为 html 文件就是其中之一。由于您正在阅读行,因此 java 必须为您正在阅读的每一行分配内存,以便将内存中复制的所有内容复制到 StringBuffer 中,这会导致密集的 GC 工作。然后 StringBuffer 具有固定大小,因此您的程序可能会达到超出 StringBuffers 大小的点,这会导致调整 StringBuffer 的大小,从而导致将 Buffer 中的所有内容复制到新的 Buffer 中。 因此,您宁愿尝试获取您请求的 html 文档的大小,并将所有内容读入 char 数组。这可能行不通,因为 http 允许以可变大小的 block 传输数据。如果是这种情况,您可以采取以下措施:
String html = "";
CharBuffer buff = CharBuffer.allocate(16384);
int read = in.read(buff);
while(read > -1) {
while(read > -1 && buff.remaining > 0) {
read = in.read(buff);
}
html += new String(buff.array());
buff.clear();
}
关于java - 如何更有效地从互联网上获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11633714/