有一个数据很多的页面,如果全部获取的话要用很久时间。
如何只获取一部分数据或者指定时间,时间到了后面剩下的就不要了

解决方案 »

  1.   

    我说的是java通过地址去获取页面的html代码,像爬虫这种
      

  2.   

    可以啊,以 HttpURLConnection 为例,在读取
    HttpURLConnection .getInputStream() 流内容时,长度达到1000后,直接返回。
      

  3.   

    例如:    private static String GetResponse(HttpURLConnection connection) throws IOException {
            int readSize = 10000; // 要读取10k字节        InputStream is = null;
            InputStreamReader reader = null;
            try {
                int code = connection.getResponseCode();
                if (code <= 399) {
                    is = connection.getInputStream();
                } else {
                    is = connection.getErrorStream();
                }
                if(is == null)
                    return "";            String contentEncoding = connection.getContentEncoding();
                if(contentEncoding != null && contentEncoding.equals("gzip")) {
                    is = new GZIPInputStream(is);
                }            // 这里不用BufferReader.readLine 避免自己加换行
                reader = new InputStreamReader(is, StandardCharsets.UTF_8);
                StringBuilder sb = new StringBuilder();
                int c;
    /////////////////////////////////////////////////////////////////
                int cnt = 0;
                while ((c = reader.read()) != -1 && cnt<readSize ){
                    sb.append((char) c); cnt++; 
                }
    /////////////////////////////////////////////////////////////////
                return sb.toString();
            } finally {
                Close(reader, is);
            }
        }