Apache httpclient Framework
Get method Request submission data
1. Create a HttpClient
New Defaulthttpclient ();
2. Create a httpget, the data to be submitted to the server has been stitched into the path
New HttpGet (path);
3. Use the HttpClient object to send a GET request, establish a connection, return the response header object
HttpResponse hr = Hc.execute (Hg);
4. Get the status line in the response header, get the status code, and if 200, the request succeeds
if (Hr.getstatusline (). Getstatuscode () = =){ The content in the entity in the response header is actually the input stream returned by the server InputStream is = hr.getentity (). getcontent (); = Utils.gettextfromstream (is);}
Post method request submission data
1. Create a HttpClient
New Defaulthttpclient ();
2. Create a HttpPost, the parameter of the constructor method is the URL
New HttpPost (path);
3. Put the data you want to submit to the server in the HttpPost object
// The data to be submitted is encapsulated in a Basicnamevaluepair object as a key-value pair Basicnamevaluepair bnvp = new Basicnamevaluepair ("name" , name); Basicnamevaluepair bnvp2 = new Basicnamevaluepair ("Pass" , pass); List <NameValuePair> parameters = new Arraylist<namevaluepair > ();p Arameters.add (BNVP);p arameters.add (BNVP2); // urlencodedformentity entity = new urlencodedformentity (Parameters, "Utf-8" Span style= "color: #000000;" >); // hp.setentity (entity) that encapsulates the data to be submitted into the output stream of the post request;
4. Use the HttpClient object to send a POST request, establish a connection, return the response header object
HttpResponse hr = Hc.execute (HP);
5. Get the status line in the response header, get the status code, and if 200, the request succeeds
if (Hr.getstatusline (). Getstatuscode () = =){ // Get the contents of the entity in the response header, which is actually the input stream returned by the server InputStream is = hr.getentity (). getcontent (); = Utils.gettextfromstream (is);}
Android-async-http Framework (based on Apache HttpClient Framework package)
The Android-async-http framework is an asynchronous httpclient framework that does not require us to create sub-threads, and the framework creates sub-threads for us to perform network interactions
Get method Request submission data
1. Create an asynchronous HttpClient
New Asynchttpclient ();
2. Send a GET request to submit data, the submitted data is stitched on the path
New Myresponsehandler ());
Post method request submission data
1. Create an asynchronous HttpClient
New Asynchttpclient ();
2. Package the data to be submitted to Requestparams
New requestparams ();p arams.add("name", name);p Arams.add ("pass", pass);
3. Send a POST request to submit data
New Myresponsehandler ());
Response Processor Asynchttpresponsehandler
classMyresponsehandlerextendsasynchttpresponsehandler{// callback This method when the request server succeeds (response code is 200)@Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] responsebody) { // responsebody content is the data returned by the serverToast.maketext (mainactivity. This,NewString (Responsebody, "GBK"), Toast.length_short). Show (); } // HTTP request failed (return code not 200), system callback this method@Override Public voidOnFailure (intStatusCode, header[] headers,byte[] responsebody, throwable error) {Toast.maketext (mainactivity). This,NewString (Responsebody, "GBK"), Toast.length_short). Show (); } }
Multi-Threaded Download
The server CPU allocates the same time slices to each thread, and the server bandwidth is evenly distributed to each thread, so the more threads the client opens, the more server resources can be preempted. In fact, the more download threads are not client concurrent, the faster the program downloads, because when the client turns on too many concurrent threads, the application needs to maintain the overhead of each thread, the overhead of thread synchronization, which can cause the download to slow down, and regardless of how many threads are running to preempt the server resources, The download bandwidth does not exceed the client's physical bandwidth
The main thread first sends an HTTP GET request to determine which part of the data each thread downloads
Get the total size of the resource file, and then create a temporary file of the same size
String Path = "http://dldir1.qq.com/music/clntupate/QQMusic.apk"; URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000);if(Conn.getresponsecode () = = 200){ intLength = Conn.getcontentlength ();//get the length of the data in the server streamRandomaccessfile RAF =NewRandomaccessfile (GetFileName (path), "RWD");//Create a temporary file to store downloaded dataRaf.setlength (length);//set the size of a temporary fileRaf.close ();
Calculate how much data each thread downloads
int blockSize = Length/thread_count;
Calculates the start and end locations of each thread's download data, and then turns on the download sub-thread
for(intid = 0; ID < ThreadCount; id++){ //calculate the starting and ending locations of each thread's download data intStartIndex = ID *blockSize; intEndIndex = (id+1) * blockSize-1; //If this is the last thread, the end position is the end of the resource file if(id = = ThreadCount-1) {EndIndex= Length-1; } //Start the thread and download the data at the end of the calculated start point NewDownloadthread (StartIndex, EndIndex, id). Start ();
Each download thread sends an HTTP GET request again, requesting that part of the data it is responsible for downloading
Request the part of the data that you are responsible for, synchronously write to the appropriate location in the temporary file
String Path = "http://dldir1.qq.com/music/clntupate/QQMusic.apk"; URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); Conn.setrequestproperty ("Range", "bytes=" + StartIndex + "-" + EndIndex);//set the data interval for this HTTP requestConn.connect ();//request part of the data, the successful response code is 206if(Conn.getresponsecode () = = 206) {InputStream is= Conn.getinputstream ();//there is only data in the 1/threadcount resource file at this time in the streamRandomaccessfile RAF =NewRandomaccessfile (GetFileName (path), "RWD"); Raf.seek (StartIndex); //move the file's write location to startindex byte[] B =New byte[1024]; intLen; while(len = Is.read (b))! =-1) {Raf.write (b,0, Len); } raf.close ();}
Multi-threaded Download with breakpoint continuation
-
Each download thread defines a threadprogress member variable that records the progress of the current thread download, and the thread writes the data to the resource temp file while recording the threadprogress and depositing the progress cache file
while (len = Is.read (b))! = -1) {Raf.write (b, 0 += Len; Randomaccessfile Progressraf = new randomaccessfile (progressfile, "RWD" ); Progressraf.write ((threadprogress + "" ). GetBytes ()); Progressraf.close ();}
The next time the download begins, the value in the cache file is read first, and the resulting value is the beginning of the line assigns
Newnew BufferedReader (new= Integer.parseint (Br.readline ()); read out the progress temp file The total progress of the last download startIndex + = threadprogress; // with the original starting position added, to get a new start position, complete the breakpoint continued to transmit fis.close ();
After all threads have been downloaded, delete the cache file
finishedthread++; if (Finishedthread = = threadcount) {for (int i = 0; i < threadcount; i++) { C9>new File (target, i + ". txt"); F.delete (); }}
Mobile version of the breakpoint continued multi-threaded downloader
Show download progress with progress bar
Set the maximum value of the progress bar when you get the total size of the download file
Pb.setmax (length); // set the maximum value of the progress bar
- The
-
Progress bar needs to show the overall download progress for all threads, so each thread downloads a new download length into the progress bar
Each time the breakpoint is downloaded, the download starts from the new starting position, and the progress bar is also displayed at the beginning of the new location, and the progress bar progress is also processed when the cache file is read to get a fresh download start location.
Newnew bufferedreader ( fis) (new InputStreamReader); // read out the progress temp file The total progress of the last download // then add to the original starting position, get a new start position, complete the breakpoint continuation threadprogress =+ = threadprogress; // display the overall progress of the last multi-threaded download to the progress bar totalprogress + = threadprogress;pb.setprogress (totalprogress);
Add a text box to show percent progress
Tv.settext ((long) pb.getprogress () * 100/pb.getmax () + "%"); // text progress is synchronized with the progress bar and converted to a long type to prevent integer overflow
Download files using the Open source framework Xutils
Open source Framework Xutils is based on the original open source framework afinal development, there are four main modules, wherein the Httputils module support breakpoint Continuation, stop downloading tasks at any time, start the task
Create a Httputils object
New Httputils ();
Download file
Http.download (Path,// Target// download the path and file name of the data save true,// whether to support breakpoint continuation true,// If there is no file name in the request address, the file name is in the response header and is automatically renamed after the download is complete NewRequestcallback<file> () {// listening for download status// callback after successful download@Override Public voidOnsuccess (responseinfo<file>responseinfo) {Toast.maketext (mainactivity). This, ResponseInfo.result.getPath (), Toast.length_short). Show (); } // callback when the download fails, such as the file has been downloaded, no network permissions, no access to the file, method passed in a string s to inform the cause of failure@Override Public voidonfailure (HttpException E, String s) {tv_failure.settext (s); } // constant calls during the download process to refresh the progress bar@Override Public voidOnloading (LongTotalLongCurrentBooleanisuploading) { Super. onloading (Total, Current, isuploading); Pb.setmax ((int) total);//set the total length of the progress barPb.setprogress ((int) (current);//Set progress bar Current ProgressTv_progress.settext (Current * 100/total + "%");//Text Progress }});
Android application Development-network Programming (ii) (re-plate)