用Java編寫的http下載工具類,包含下載進度回調

來源:互聯網
上載者:User

標籤:while   ttext   jframe   this   span   finally   load   interface   als   

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下載工具類,包含下載進度回調

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.