HttpURLConnection方式下载文件之实现断点续传
2016-08-19 19:52
1521 查看
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(); } } }
相关文章推荐
- andorid学习之利用HttpURLConnection对象实现文件下载
- HttpURLConnection实现文件下载
- HttpUrlConnection实现文件下载
- 使用HttpURLConnection实现文件下载
- HttpURLConnection实现文件断点续传
- android开发之HttpUrlConnection与OkHttp实现文件上传下载
- 运用java.net.HttpURLConnection实现java多线程下载文件
- HttpURLConnection方式文件下载之多线程下载
- HttpURLConnection实现文件下载,Service加Notification实现后台下载
- 利用HttpURLConnection实现远程下载文件
- android网络编程之HttpUrlConnection的讲解--实现文件断点下载
- android httpUrlConnection 方式从网络上面下载图片
- 06_android入门_采用HttpURLConnection的POST方式实现登陆案例
- Android_HttpURLConnection下载文件
- JAVA使用HttpUrlConnection实现自动上传文件
- 关于inputStream.available()与HttpURLConnection.getContentLength()方法获取下载文件的大小
- 04_android入门_采用HttpURLConnection的GET方式实现登陆案例
- 下载网络文件HttpURLConnection.getContentLength()大小为
- 用httpUrlConnection实现文件上传
- c#实现 ftp ;http;共享方式下载文件 并对比本地文件和服务器文件的更新时间 判断性下载