HttpDownloader.java

  1. package com.buyishi;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8.  
  9. public class HttpDownloader {
  10.  
  11. private final String url, destFilename;
  12.  
  13. public HttpDownloader(String url, String destFilename) {
  14. this.url = url;
  15. this.destFilename = destFilename;
  16. }
  17.  
  18. public void download(Callback callback) {
  19. try (FileOutputStream fos = new FileOutputStream(destFilename)) {
  20. URLConnection connection = new URL(url).openConnection();
  21. long fileSize = connection.getContentLengthLong();
  22. InputStream inputStream = connection.getInputStream();
  23. byte[] buffer = new byte[10 * 1024 * 1024];
  24. int numberOfBytesRead;
  25. long totalNumberOfBytesRead = 0;
  26. while ((numberOfBytesRead = inputStream.read(buffer)) != - 1) {
  27. fos.write(buffer, 0, numberOfBytesRead);
  28. totalNumberOfBytesRead += numberOfBytesRead;
  29. callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
  30. }
  31. callback.onFinish();
  32. } catch (IOException ex) {
  33. callback.onError(ex);
  34. }
  35. }
  36.  
  37. public interface Callback {
  38.  
  39. void onProgress(long progress);
  40.  
  41. void onFinish();
  42.  
  43. void onError(IOException ex);
  44. }
  45. }

OkHttpDownloader.java  //基于OkHttp

  1. package com.buyishi;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8. import okhttp3.OkHttpClient;
  9. import okhttp3.Request;
  10. import okhttp3.ResponseBody;
  11.  
  12. public class OkHttpDownloader {
  13.  
  14. private final String url, destFilename;
  15. private static final Logger LOGGER = Logger.getLogger(OkHttpDownloader.class.getName());
  16.  
  17. public OkHttpDownloader(String url, String destFilename) {
  18. this.url = url;
  19. this.destFilename = destFilename;
  20.  
  21. }
  22.  
  23. public void download(Callback callback) {
  24. BufferedInputStream input = null;
  25. try (FileOutputStream fos = new FileOutputStream(destFilename)) {
  26. Request request = new Request.Builder().url(url).build();
  27. ResponseBody responseBody = new OkHttpClient().newCall(request).execute().body();
  28. long fileSize = responseBody.contentLength();
  29. input = new BufferedInputStream(responseBody.byteStream());
  30. byte[] buffer = new byte[10 * 1024 * 1024];
  31. int numberOfBytesRead;
  32. long totalNumberOfBytesRead = 0;
  33. while ((numberOfBytesRead = input.read(buffer)) != - 1) {
  34. fos.write(buffer, 0, numberOfBytesRead);
  35. totalNumberOfBytesRead += numberOfBytesRead;
  36. callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
  37. }
  38. callback.onFinish();
  39. } catch (IOException ex) {
  40. callback.onError(ex);
  41. } finally {
  42. if (input != null) {
  43. try {
  44. input.close();
  45. } catch (IOException ex) {
  46. LOGGER.log(Level.SEVERE, null, ex);
  47. }
  48. }
  49. }
  50. }
  51.  
  52. public interface Callback {
  53.  
  54. void onProgress(long progress);
  55.  
  56. void onFinish();
  57.  
  58. void onError(IOException ex);
  59. }
  60. }

MainFrame.java  //对两个工具类的测试

  1. package com.buyishi;
  2.  
  3. import java.awt.GridLayout;
  4. import java.awt.event.MouseAdapter;
  5. import java.awt.event.MouseEvent;
  6. import java.io.IOException;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9. import javax.swing.JButton;
  10. import javax.swing.JFrame;
  11.  
  12. public class MainFrame extends JFrame {
  13.  
  14. private final JButton test1Button, test2Button;
  15. private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName());
  16.  
  17. private MainFrame() {
  18. super("Download Test");
  19. super.setSize(300, 200);
  20. super.setLocationRelativeTo(null);
  21. super.setDefaultCloseOperation(EXIT_ON_CLOSE);
  22. super.setLayout(new GridLayout(2, 1));
  23. test1Button = new JButton("测试1");
  24. test2Button = new JButton("测试2");
  25. super.add(test1Button);
  26. super.add(test2Button);
  27. test1Button.addMouseListener(new MouseAdapter() {
  28. private boolean downloadStarted;
  29.  
  30. @Override
  31. public void mouseClicked(MouseEvent e) {
  32. if (!downloadStarted) {
  33. downloadStarted = true;
  34. new Thread() {
  35. @Override
  36. public void run() {
  37. String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
  38. // String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
  39. new HttpDownloader(url, "C:/Users/BuYishi/Desktop/file1").download(new HttpDownloader.Callback() {
  40. @Override
  41. public void onProgress(long progress) {
  42. LOGGER.log(Level.INFO, "{0}", progress);
  43. test1Button.setText("Downloading..." + progress + "%");
  44. }
  45.  
  46. @Override
  47. public void onFinish() {
  48. LOGGER.log(Level.INFO, "Download finished");
  49. test1Button.setText("Downloaded");
  50. }
  51.  
  52. @Override
  53. public void onError(IOException ex) {
  54. LOGGER.log(Level.SEVERE, null, ex);
  55. downloadStarted = false;
  56. }
  57. });
  58. }
  59. }.start();
  60. }
  61. }
  62. });
  63. test2Button.addMouseListener(new MouseAdapter() {
  64. private boolean downloadStarted;
  65.  
  66. @Override
  67. public void mouseClicked(MouseEvent e) {
  68. if (!downloadStarted) {
  69. downloadStarted = true;
  70. new Thread() {
  71. @Override
  72. public void run() {
  73. String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
  74. // String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
  75. new OkHttpDownloader(url, "C:/Users/BuYishi/Desktop/file2").download(new OkHttpDownloader.Callback() {
  76. @Override
  77. public void onProgress(long progress) {
  78. test2Button.setText("Downloading..." + progress + "%");
  79. }
  80.  
  81. @Override
  82. public void onFinish() {
  83. test2Button.setText("Downloaded");
  84. }
  85.  
  86. @Override
  87. public void onError(IOException ex) {
  88. LOGGER.log(Level.SEVERE, null, ex);
  89. downloadStarted = false;
  90. }
  91. });
  92. }
  93. }.start();
  94. }
  95. }
  96. });
  97. }
  98.  
  99. public static void main(String[] args) {
  100. MainFrame frame = new MainFrame();
  101. frame.setVisible(true);
  102. }
  103. }

用Java编写的http下载工具类,包含下载进度回调的更多相关文章

  1. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  2. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  3. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

  4. Java汉字转成汉语拼音工具类

    Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...

  5. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  6. java中定义一个CloneUtil 工具类

    其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...

  7. java代码行数统计工具类

    package com.syl.demo.test; import java.io.*; /** * java代码行数统计工具类 * Created by 孙义朗 on 2017/11/17 0017 ...

  8. Java加载Properties配置文件工具类

    Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...

  9. Java 操作Redis封装RedisTemplate工具类

    package com.example.redisdistlock.util; import org.springframework.beans.factory.annotation.Autowire ...

  10. java后台表单验证工具类

    /** * 描述 java后台表单验证工具类 * * @ClassName ValidationUtil * @Author wzf * @DATE 2018/10/27 15:21 * @VerSi ...

随机推荐

  1. nginx中access_log和nginx.conf中的log_format用法

    nginx服务器日志相关指令主要有两条: 一条是log_format,用来设置日志格式; 另外一条是access_log,用来指定日志文件的存放路径.格式和缓存大小 可以参加ngx_http_log_ ...

  2. 【Luogu】P2059卡牌游戏(概率DP)

    题目链接 这绝壁是道紫难度的题 请移步xyz32678的题解. 设f[i][j]是有i个人参加了游戏,1是庄家,最后j胜出的概率. 我们可以发现,这个游戏影响胜出的概率的只有庄家的相对位置和人数,跟玩 ...

  3. BZOJ 2286 [Sdoi2011]消耗战 ——虚树

    虚树第一题. 大概就是建一颗只与询问有关的更小的新树,然后在虚树上DP #include <map> #include <ctime> #include <cmath&g ...

  4. 算法总结——主席树(poj2104)

    题目: Description You are working for Macrohard company in data structures department. After failing y ...

  5. getParameter 与 getAttribute的区别

    request.getAttribute():是request时设置的变量的值,用request.setAttribute("name","您自己的值");来设 ...

  6. STL中heap用法

    #include<cstdio> #include<iostream> #include<algorithm> using namespace std; ]={,, ...

  7. Python入门--8--现在需要先学习可视化--包:easygui

    一.安装.了解easygui 下载地址:http://bbs.fishc.com/forum.php?mod=viewthread&tid=46069&extra=page%3D1%2 ...

  8. laravel 的模型

    建立model文件,再项目的app目录下建立Member.php namespace App; use Illuminate\Database\Eloquent\Model; class Member ...

  9. SPOJ 1479 +SPOJ 666 无向树最小点覆盖 ,第二题要方案数,树形dp

    题意:求一颗无向树的最小点覆盖. 本来一看是最小点覆盖,直接一下敲了二分图求最小割,TLE. 树形DP,叫的这么玄乎,本来是线性DP是线上往前\后推,而树形DP就是在树上,由叶子结点状态向根状态推. ...

  10. LeetCode OJ--Remove Duplicates from Sorted List II *

    http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 处理链表的范例 #include <iostream ...