HttpDownloader.java

package com.buyishi;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; public class HttpDownloader { private final String url, destFilename; public HttpDownloader(String url, String destFilename) {
this.url = url;
this.destFilename = destFilename;
} public void download(Callback callback) {
try (FileOutputStream fos = new FileOutputStream(destFilename)) {
URLConnection connection = new URL(url).openConnection();
long fileSize = connection.getContentLengthLong();
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[10 * 1024 * 1024];
int numberOfBytesRead;
long totalNumberOfBytesRead = 0;
while ((numberOfBytesRead = inputStream.read(buffer)) != - 1) {
fos.write(buffer, 0, numberOfBytesRead);
totalNumberOfBytesRead += numberOfBytesRead;
callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
}
callback.onFinish();
} catch (IOException ex) {
callback.onError(ex);
}
} public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex);
}
}

OkHttpDownloader.java  //基于OkHttp

package com.buyishi;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody; public class OkHttpDownloader { private final String url, destFilename;
private static final Logger LOGGER = Logger.getLogger(OkHttpDownloader.class.getName()); public OkHttpDownloader(String url, String destFilename) {
this.url = url;
this.destFilename = destFilename; } public void download(Callback callback) {
BufferedInputStream input = null;
try (FileOutputStream fos = new FileOutputStream(destFilename)) {
Request request = new Request.Builder().url(url).build();
ResponseBody responseBody = new OkHttpClient().newCall(request).execute().body();
long fileSize = responseBody.contentLength();
input = new BufferedInputStream(responseBody.byteStream());
byte[] buffer = new byte[10 * 1024 * 1024];
int numberOfBytesRead;
long totalNumberOfBytesRead = 0;
while ((numberOfBytesRead = input.read(buffer)) != - 1) {
fos.write(buffer, 0, numberOfBytesRead);
totalNumberOfBytesRead += numberOfBytesRead;
callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
}
callback.onFinish();
} catch (IOException ex) {
callback.onError(ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
} public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex);
}
}

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

package com.buyishi;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame; public class MainFrame extends JFrame { private final JButton test1Button, test2Button;
private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName()); private MainFrame() {
super("Download Test");
super.setSize(300, 200);
super.setLocationRelativeTo(null);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setLayout(new GridLayout(2, 1));
test1Button = new JButton("测试1");
test2Button = new JButton("测试2");
super.add(test1Button);
super.add(test2Button);
test1Button.addMouseListener(new MouseAdapter() {
private boolean downloadStarted; @Override
public void mouseClicked(MouseEvent e) {
if (!downloadStarted) {
downloadStarted = true;
new Thread() {
@Override
public void run() {
String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
// String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
new HttpDownloader(url, "C:/Users/BuYishi/Desktop/file1").download(new HttpDownloader.Callback() {
@Override
public void onProgress(long progress) {
LOGGER.log(Level.INFO, "{0}", progress);
test1Button.setText("Downloading..." + progress + "%");
} @Override
public void onFinish() {
LOGGER.log(Level.INFO, "Download finished");
test1Button.setText("Downloaded");
} @Override
public void onError(IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
downloadStarted = false;
}
});
}
}.start();
}
}
});
test2Button.addMouseListener(new MouseAdapter() {
private boolean downloadStarted; @Override
public void mouseClicked(MouseEvent e) {
if (!downloadStarted) {
downloadStarted = true;
new Thread() {
@Override
public void run() {
String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
// String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
new OkHttpDownloader(url, "C:/Users/BuYishi/Desktop/file2").download(new OkHttpDownloader.Callback() {
@Override
public void onProgress(long progress) {
test2Button.setText("Downloading..." + progress + "%");
} @Override
public void onFinish() {
test2Button.setText("Downloaded");
} @Override
public void onError(IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
downloadStarted = false;
}
});
}
}.start();
}
}
});
} public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
}

用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. RDDs基本操作、RDDs特性、KeyValue对RDDs、RDD依赖

    摘要:RDD是Spark中极为重要的数据抽象,这里总结RDD的概念,基本操作Transformation(转换)与Action,RDDs的特性,KeyValue对RDDs的Transformation ...

  2. [UOJ#219][BZOJ4650][Noi2016]优秀的拆分

    [UOJ#219][BZOJ4650][Noi2016]优秀的拆分 试题描述 如果一个字符串可以被拆分为 AABBAABB 的形式,其中 A 和 B 是任意非空字符串,则我们称该字符串的这种拆分是优秀 ...

  3. AOP面向方面(切面)编程

    1.引言 软件开发的目标是要对世界的部分元素或者信息流建立模型,实现软件系统的工程需要将系统分解成可以创建和管理的模块.于是出现了以系统模块化特性的面向对象程序设计技术.模块化的面向对象编程极度极地提 ...

  4. Codeforces Round #265 (Div. 2) C 暴力+ 找规律+ 贪心

    C. No to Palindromes! time limit per test 1 second memory limit per test 256 megabytes input standar ...

  5. AttributeError: module 're' has no attribute 'search'

    命名py脚本时,不要与python预留字,模块名等相同,即Python文件名不要使用Python系统库的名字,就是因为使用了Python系统库的名字,所以在编译的时候才会产生.pyc文件.正常的Pyt ...

  6. android连数据库

    package com.rockcheck.mes; import android.os.AsyncTask; import android.support.v7.app.AppCompatActiv ...

  7. HDU - 5584 LCM Walk (数论 GCD)

    A frog has just learned some number theory, and can't wait to show his ability to his girlfriend. No ...

  8. windows下安装python、环境设置、多python版本的切换、pyserial与多版本python安装、windows命令行下切换目录

    1.windows下安装python 官网下载安装即可 2.安装后的环境设置 我的电脑--属性--高级--设置path的地方添加python安装目录,如C:\Python27;C:\Python33 ...

  9. codeforces #472(div 1)

    B(two point) 题意: 给出长度为n的非递减数组E[1..n],对于所有三元组(i,j,k),1<=i<j<k<=n且Ek-Ei<=U,我们需要计算出最大的(E ...

  10. 【mac】显示隐藏文件夹

    进入访达 快捷键:command+shift+.