Multi-thread download using httpurlconnection

Source: Internet
Author: User

Httpurlconnection inherits urlconnection. Therefore, it can also be used to send GET requests and post requests to a specified website. In addition, it provides the following convenient methods based on urlconnection:

To download multiple threads:

The following example demonstrates how to use httpurlconnection to implement multi-threaded download. The main idea of this Code is to click a button in the activity, call the download () method of downutil, and start four threads in download () to download resources, each thread is responsible for downloading its own resources. The Code is as follows:

Activity:

Package COM. home. activity; import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. progressbar; import COM. home. multithreaddown. r; import COM. home. util. downutil; public class multithreaddownactivity extends activity {private edittext urltext; private edittext targettext; private button downbtn; private progressbar bar; private downutil; private int mdownstatus; private handler; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // obtain the control targettext = (edittext) findviewbyid (R. id. main_et_name); urltext = (edittext) findviewbyid (R. id. main_et_url); downbtn = (button) findviewbyid (R. id. main_btn_download); bar = (progressbar) findviewbyid (R. id. main_progressbar); // create a handler Object Handler = new handler () {public void handlemessage (Message MSG) {If (MSG. what = 0x123) {bar. setprogress (mdownstatus) ;}}; downbtn. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// initialize the downutil object downutil = new downutil (urltext. gettext (). tostring (), targettext. gettext (). tostring (), 4); try {// start downloading downutil. download ();} catch (exception e) {e. printstacktrace ();} // defines the progress of system completion obtained by scheduling every second. Final timer = new timer (); timer. schedule (New timertask () {public void run () {// obtain the download task completion rate double completerate = downutil. getcompleterate (); mdownstatus = (INT) (completerate * 100); // update the progress bar handler on the Send Message notification page. sendemptymessage (0x123); // After the download is complete, cancel the task scheduling if (mdownstatus> = 100) {timer. cancel () ;}}, 0,100 );}});}}

Downloading tool class (downutil ):

Package COM. home. util; import Java. io. inputstream; import Java. io. randomaccessfile; import java.net. httpurlconnection; import java.net. URL; public class downutil {// defines the download resource path private string path; // specifies the storage location of the downloaded file private string targetfile; // define how many threads need to be used to download resources private int threadnum; // define the total size of the downloaded file private int filesize; // define the downloaded thread object private downloadthread [] threads; public downutil (string path, string targetfile, in T threadnum) {This. path = path; this. threadnum = threadnum; // initialize the threads array threads = new downloadthreadthreads threadnum;;this.tar GetFile = targetfile;} public void download () throws exception {URL url = new URL (PATH ); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5*1000); Conn. setrequestmethod ("get"); Conn. setrequestproperty ("accept", "image/GIF, image/JPEG, image/pjp Eg, application/X-shockwaveflash, application/X-MS-xbap, application/XAML + XML, application/vnd. MS-xpsdocument, application/X-MS-application, application/vnd. MS-Excel, application/vnd. MS-PowerPoint, application/MSWord, */* "); Conn. setrequestproperty ("Accept-language", "ZH-CN"); Conn. setrequestproperty ("charset", "UTF-8"); Conn. setrequestproperty ("User-Agent", "Mozilla/4.0 (compatible; msie7.0; Windows NT 5.2; tride NT/4.0 ;. net CLR 1.1.4322 ;. net CLR 2.0.50727 ;. net CLR 3.0.04506.30 ;. net CLR 3.0.20.6.2152 ;. net CLR 3.5.30729) "); Conn. setrequestproperty ("connection", "keep-alive"); // obtain the file size filesize = Conn. getcontentlength (); Conn. disconnect (); int currentpartsize = filesize/threadnum + 1; randomaccessfile file = new randomaccessfile (targetfile, "RW"); // set the local file size file. setlength (filesize); file. close (); For (INT I = 0; I <threadnum; I ++) {// calculate the start position of each thread's download. Int startpos = I * currentpartsize; // each thread uses a randomaccessfile to download randomaccessfile currentpart = new randomaccessfile (targetfile, "RW"); // locate the download location of the thread currentpart. seek (startpos); // create the download thread threads [I] = new downloadthread (startpos, currentpartsize, currentpart); // start the download thread threads [I]. start () ;}}/*** get the download completion percentage ** @ return */Public double getcompleterate () {// count that multiple threads have been downloaded Total load size int sumsize = 0; For (INT I = 0; I <threadnum; I ++) {sumsize + = threads [I]. length ;}/// return the percentage of completed results. Return sumsize * 1.0/filesize;} private class downloadthread extends thread {// The download location of the current thread, private int startpos; // defines the file size private int currentpartsize that the current thread is responsible for downloading; // The file block private randomaccessfile currentpart to be downloaded by the current thread; // defines the number of bytes downloaded by this thread. Private int length = 0; Public downloadthread (INT startpos, int currentparts Ize, randomaccessfile currentpart) {This. startpos = startpos; this. currentpartsize = currentpartsize; this. currentpart = currentpart;} public void run () {try {URL url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5*1000); Conn. setrequestmethod ("get"); Conn. setrequestproperty ("accept", "image/GIF, image/JPEG, image/pjpeg, application/X-shockwavefla Sh, application/X-MS-xbap, application/XAML + XML, application/vnd. MS-xpsdocument, application/X-MS-application, application/vnd. MS-Excel, application/vnd. MS-PowerPoint, application/MSWord, */* "); Conn. setrequestproperty ("Accept-language", "ZH-CN"); Conn. setrequestproperty ("charset", "UTF-8"); inputstream is = Conn. getinputstream (); // skip the startpos character, indicating that the thread only downloads the part of the file that it is responsible. skip (startpos); byte [] by = new byte [1024]; Int hasread = 0; // read network data and write it to the local file while (length <currentpartsize & (hasread = is. Read ())! =-1) {currentpart. write (by, 0, hasread); // The total download size of this thread. Length + = hasread;} currentpart. close (); is. close ();} catch (exception e) {e. printstacktrace ();}}}}

Activity layout XML:

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: Orientation = "vertical"> <linearlayout Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: Orientation = "horizontal"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "input URL:"/> <edittext Android: Id = "@ + ID/main_et_url" Android: layout_width = "match_parent" Android: layout_height = "wrap_content"/> </linearlayout> <linearlayout Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: Orientation = "horizontal"> <textview android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Enter the saved file name:"/> <edittext Android: Id = "@ + ID/main_et_name" Android: layout_width = "match_parent" Android: layout_height = "wrap_content"/> </linearlayout> <button Android: Id = "@ + ID/main_btn_download" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "Download"/> <progressbar Android: Id = "@ + ID/main_progressbar" style = "@ Android: style/widget. progressbar. horizontal "Android: layout_width =" match_parent "Android: layout_height =" wrap_content "/> </linearlayout>

Permission:

<! -- Create and delete file permissions on the SD card --> <uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/> <! -- Write data permission to SD card --> <uses-Permission Android: Name = "android. Permission. write_external_storage"/> <! -- Authorize access to the network --> <uses-Permission Android: Name = "android. Permission. Internet"/>

 

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.