1. 程式人生 > >HttpURLConnection方式下載檔案之實現斷點續傳

HttpURLConnection方式下載檔案之實現斷點續傳

public class DownloadTest {
    public static void main(String[] args) {
        try {
            File file = new File("test.apk");
            HttpURLConnection connection = (HttpURLConnection) new URL("http://skycnxz2.wy119.com/4/wandoujia.apk").openConnection();
            connection.setRequestMethod("GET");
            long sum = 0;
            if (file.exists()) {
                sum = file.length();
                /*
                *
                * GET /down.zip HTTP/1.0
                * User-Agent: NetFox
                * RANGE: bytes=2000070-
                 */
                // 設定斷點續傳的開始位置
                connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
            }
            int code = connection.getResponseCode();
            System.out.println("code = " + code);
            if (code == 200 || code == 206) {
//                Map<String, List<String>> fields = connection.getHeaderFields();
//                for (Map.Entry<String, List<String>> entry : fields.entrySet()) {
//                    System.out.println(entry.getKey());
//                    System.out.println(entry.getValue());
//                    System.out.println("===================");
//                }
                int contentLength = connection.getContentLength();
                System.out.println("contentLength = " + contentLength);
                contentLength += sum;
                InputStream is = connection.getInputStream();
                /*
                *
                * 建立一個向具有指定 name 的檔案中寫入資料的輸出檔案流。
                * true表示當檔案在下載過程中出現中斷,
                * 當再次連結網路時,將會從斷點處追加。
                *
                * */
                FileOutputStream fos = new FileOutputStream(file, true);

                byte[] buffer = new byte[102400];
                int length;
                long startTime = System.currentTimeMillis();
                while ((length = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                    sum += length;
                    float percent = sum * 100.0f / contentLength;
                    System.out.print("\r[");
                    int p = (int) percent / 2;
                    /*
                    * 實現進度條
                    * */
                    for (int i = 0; i < 50; i++) {
                        if (i < p) {
                            System.out.print('=');
                        } else if (i == p){
                            System.out.print('>');
                        } else {
                            System.out.print(' ');
                        }
                    }
                    System.out.print(']');
                    System.out.printf("\t%.2f%%", percent);
                    long speed = sum * 1000 / (System.currentTimeMillis() - startTime);
                    if (speed > (1 << 20)) {
                        System.out.printf("\t%d MB/s", speed >> 20);
                    } else if (speed > (1 << 10)) {
                        System.out.printf("\t%d KB/s", speed >> 10);
                    } else {
                        System.out.printf("\t%d B/s", speed);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}