用Java编写的http下载工具类,包含下载进度回调

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);
    }
}

原文地址:https://www.cnblogs.com/buyishi/p/9379930.html

时间: 2024-10-14 04:24:20

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

Java随机取字符串的工具类

原文:Java随机取字符串的工具类 源代码下载地址:http://www.zuidaima.com/share/1550463479532544.htm Java 随机取字符串的工具类 可以全部是数字,字符,也可以字符和数字组合的工具类,希望能给大家带来帮助 package com.zuidaima.test; import java.util.Random; public class RandomUtils { public static final String ALLCHAR = "012

java HTML字符串正则表达式使用工具类

原文:java HTML字符串正则表达式使用工具类 代码下载地址:http://www.zuidaima.com/share/1550463453416448.htm HTML相关的正则表达式工具类 包括过滤HTML标记,转换HTML标记,替换特定HTML标记 package com.zuidaima.common.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * Title: H

HttpUtils.java 网络下载工具类

package Http; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL; /** * 网络下载工具类 * 功能:下载字节数组,下载文本数据 * 下载数字数组(文本 图片 mp3) * 下载文本数据 * Created by lxj-pc on 2017/

java ftp 上传下载工具类

1 package com.mohecun.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStre

Http02App 整合两个工具类实现下载文件

Http02App.java1.使用两个工具类 实现下载音乐和图片到本地硬盘中 package main; import Http.FileUtils;import Http.HttpUtils; import java.io.IOException; /** * Created by lxj-pc on 2017/6/27. */public class Http02App { static String imgurl = "https://ss0.bdstatic.com/5aV1bjqh_

JDBC:编写通用的 JDBCUtils工具类

基本上已经可以应付常用方法 1.为JDBCUtils 添加事务处理方法 2.处理多线程并发访问问题 package cn.cil.Utls; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 编写通用的 JDB

ListView add EmptyView 工具类和下载工具类

public class EmptyViewUtils {     public static View createLoadingView(Context context) {         LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.list_empty_loading, null);         linearLayout.setLayoutParams

FTP 上传下载工具类

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import o

java实现发邮件的工具类,方便 好用(需要架包的Send Email To me)

原文:java实现发邮件的工具类,方便 好用(需要架包的Send Email To me) 源代码下载地址:http://www.zuidaima.com/share/1550463394794496.htm package com.zuidaima.util; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; impor

自定义-网络图片下载工具类

CreateTime--2017年9月30日11:18:19 Author:Marydon 网络图片下载工具类 说明:根据网络URL获取该网页上面所有的img标签并下载符合要求的所有图片 所需jar包:jsoup.jar import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.