HTTP download Tool class written in Java with download progress callback

Source: Internet
Author: User

Httpdownloader.java

 PackageCom.buyishi;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.net.URL;Importjava.net.URLConnection; Public classHttpdownloader {Private FinalString URL, destfilename;  Publichttpdownloader (string url, string destfilename) { This. url =URL;  This. destFileName =destFileName; }     Public voidDownload (Callback Callback) {Try(FileOutputStream fos =NewFileOutputStream (destFileName)) {URLConnection Connection=Newurl (url). OpenConnection (); LongFileSize =Connection.getcontentlengthlong (); InputStream InputStream=Connection.getinputstream (); byte[] buffer =New byte[10 * 1024 * 1024]; intNumberofbytesread; LongTotalnumberofbytesread = 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 InterfaceCallback {voidOnProgress (Longprogress); voidonfinish (); voidOnError (IOException ex); }}

Okhttpdownloader.java //based on Okhttp

 PackageCom.buyishi;ImportJava.io.BufferedInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.util.logging.Level;ImportJava.util.logging.Logger;ImportOKHTTP3. okhttpclient;ImportOKHTTP3. Request;ImportOKHTTP3. Responsebody; Public classOkhttpdownloader {Private FinalString URL, destfilename; Private Static FinalLogger Logger = Logger.getlogger (okhttpdownloader.class. GetName ());  Publicokhttpdownloader (string url, string destfilename) { This. url =URL;  This. destFileName =destFileName; }     Public voidDownload (Callback Callback) {bufferedinputstream input=NULL; Try(FileOutputStream fos =NewFileOutputStream (destFileName)) {Request Request=Newrequest.builder (). URL (URL). build (); Responsebody Responsebody=Newokhttpclient (). Newcall (Request). Execute (). body (); LongFileSize =responsebody.contentlength (); Input=NewBufferedinputstream (Responsebody.bytestream ()); byte[] buffer =New byte[10 * 1024 * 1024]; intNumberofbytesread; LongTotalnumberofbytesread = 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 InterfaceCallback {voidOnProgress (Longprogress); voidonfinish (); voidOnError (IOException ex); }}

Mainframe.java //test for two tool classes

 PackageCom.buyishi;Importjava.awt.GridLayout;ImportJava.awt.event.MouseAdapter;Importjava.awt.event.MouseEvent;Importjava.io.IOException;ImportJava.util.logging.Level;ImportJava.util.logging.Logger;ImportJavax.swing.JButton;ImportJavax.swing.JFrame; Public classMainFrameextendsJFrame {Private FinalJButton Test1button, Test2button; Private Static FinalLogger Logger = Logger.getlogger (MainFrame.class. GetName ()); PrivateMainFrame () {Super("Download Test"); Super. setSize (300, 200); Super. Setlocationrelativeto (NULL); Super. Setdefaultcloseoperation (Exit_on_close); Super. setlayout (NewGridLayout (2, 1)); Test1button=NewJButton ("Test 1"); Test2button=NewJButton ("Test 2"); Super. Add (Test1button); Super. Add (Test2button); Test1button.addmouselistener (NewMouseadapter () {Private Booleandownloadstarted; @Override Public voidmouseclicked (MouseEvent e) {if(!downloadstarted) {downloadstarted=true; NewThread () {@Override Public voidrun () {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";                            NewHttpdownloader (URL, "C:/users/buyishi/desktop/file1"). Download (NewHttpdownloader.callback () {@Override Public voidOnProgress (Longprogress) {LOGGER.log (Level.info,' {0} ', progress); Test1button.settext ("Downloading ..." + progress + "%"); } @Override Public voidonfinish () {LOGGER.log (Level.info,"Download finished"); Test1button.settext ("Downloaded"); } @Override Public voidOnError (IOException ex) {LOGGER.log (Level.severe,NULL, ex); Downloadstarted=false;                        }                            });                }}.start ();        }            }        }); Test2button.addmouselistener (NewMouseadapter () {Private Booleandownloadstarted; @Override Public voidmouseclicked (MouseEvent e) {if(!downloadstarted) {downloadstarted=true; NewThread () {@Override Public voidrun () {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";                            NewOkhttpdownloader (URL, "C:/users/buyishi/desktop/file2"). Download (NewOkhttpdownloader.callback () {@Override Public voidOnProgress (Longprogress) {Test2button.settext ("Downloading ..." + progress + "%"); } @Override Public voidonfinish () {Test2button.settext ("Downloaded"); } @Override Public voidOnError (IOException ex) {LOGGER.log (Level.severe,NULL, ex); Downloadstarted=false;                        }                            });                }}.start ();    }            }        }); }     Public Static voidMain (string[] args) {MainFrame frame=NewMainFrame (); Frame.setvisible (true); }}

HTTP download Tool class written in Java with download progress callback

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.