2

在我的应用程序中,我从公共 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();
                }
            }
        }
    }   
}
4

1 回答 1

0

使用 StringBuffer 下载大文本确实效率不高,因为 html 文件就是其中之一。由于您正在阅读行 java 必须为您正在阅读的每一行分配内存,只是为了将内存中复制的所有内容复制到 StringBuffer 中,这会导致密集的 GC 工作。然后 StringBuffer 具有固定大小,因此您的程序可能会达到超出 StringBuffers 大小的点,这会导致调整 StringBuffer 的大小,从而导致将 Buffer 中的所有内容复制到新的中。因此,您宁愿尝试获取您请求的 html 文档的大小,并将所有内容读入 char 数组。这可能行不通,因为 http 允许以可变大小的块传输数据。如果是这种情况,这是您可以做什么的想法:

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();
}
于 2012-07-24T15:25:27.617 回答