HttpURLConnection实现文件下载

public class DownloadTest {
    public static void main(String[] args) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL("http://skycnxz2.wy119.com/4/wandoujia.apk.apk").openConnection();
            connection.setRequestMethod("GET");
            int code = connection.getResponseCode();
            if (code == 200) {
//                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();
                InputStream is = connection.getInputStream();
                FileOutputStream fos = new FileOutputStream("test.apk");
                long sum = 0;
                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 parent = sum * 100.0f / contentLength;
                    System.out.print("\r[");
                    int p = (int) parent / 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%%", parent);
                    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();
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值