用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值