Android Network Programming

Source: Internet
Author: User

HttpClient sending a GET request
  • Create a Client Object

    HttpClient client = new Defaulthttpclient ();

  • Create a GET Request object

    HttpGet hg = new HttpGet (path);

  • Send GET request, establish connection, return response header Object

    HttpResponse hr = Hc.execute (Hg);

  • Gets the status line object, gets the status code, and if 200 indicates the request was successful

    Send a POST request
    Create a Client object     new Defaulthttpclient ();    //Create a POST request object    new HttpPost (path);  
  • Put the data you want to submit to the server in the Post object
    The data to be submitted in the form of a key-value pair exists in the Basicnamevaluepair object in the  new ArrayList ();  New Basicnamevaluepair ("name", name);  New Basicnamevaluepair ("pass", pass); parameters.  Add (BNVP); Parameters. //Set entity hp.setentity (entities) for POST request;      
    Asynchronous HttpClient framework sends a GET request
        Creates an asynchronous HttpClient object    new Asynchttpclient ();    //Send GET Request    AHC.  New MyHandler ());  
  • Note the call timing of the Asynchttpresponsehandler two methods
    ClassMyHandlerExtendsasynchttpresponsehandler{HTTP request succeeded, return code is 200, system callback this method@OverridePublicvoidOnsuccess (int StatusCode, header[] headers,// The content of Responsebody is the data returned by the server byte[] responsebody) {Toast.maketext (Mainactivity.this, new String (responsebody), 0). Show (); Span class= "Hljs-comment" >//http request failed with return code not 200, system callback this method  @Override public void  Onfailure (int StatusCode, header[] headers, byte[] responsebody, throwable error) {Toast.maketext (Mainactivity. "return code is not", 0). Show ();}}      
  • Encapsulate the data to be submitted in the RP object, instead of stitching the object like a previous GET request
    Requestparams rp = new Requestparams ();  Rp. put (name);  Rp. put ("pass", pass);   
    Send a POST request
  • Encapsulate the data to be carried using the Requestparams object
    Create an asynchronous HttpClient object  new Asynchttpclient ();  //Create Requestparams package to carry the data  new Requestparams ();  Rp. Add ("name", name), Rp.  Add (new MyHandler ());      
    Multi-Threaded Download
  • Multithreading: Fast

    *   principle: preemption Server resources
    *   单线程下载:线程从第0个字节开始下,下到最后一个字节,在本地硬盘的临时文件中从第0个字节开始写,写到最后一个字节,下载完成时,临时文件也写完了,本地就创建了一个与服务器文件一模一样的文件
    • Multi-Threaded Download: The Start and end locations of each thread download are different, and the data downloaded by each thread together is the complete file of the server
      多线程的每个线程给一个ID

      每个线程的开始位置:id*size
      每个线程的结束位置:
      (id+1)*size-1
      最后一个线程的结束位置:总长度-1
  • Breakpoint Continuation: Downloaded from the location where the last download ended

    > Principle: The server CPU allocates the same time slices to each thread, and the server bandwidth is allocated evenly to each thread, so the more threads the client opens, the more server resources can be preempted
     确定每条线程下载多少数据
  • send HTTP request to
      String Path =  "http://192.168.1.102:8080/      Editplus.exe ";  url URL = new url (path);  HttpURLConnection conn = (httpurlconnection) url.openconnection ();  Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000) Conn.setrequestmethod ( 
  • Get the total length of the file, and then create a temporary file of the same length
    if (conn.getresponsecode () = =) {      //Gets the length of the data in the server stream      int length = Conn.getcontentlength ();      //Create a temporary file to store downloaded data      //Set the size of the temp file raf.setlength (length); Raf. close ();     
  • Determine how much data the thread downloads
    Calculate how much data each thread downloads       length/thread_count;
    Calculate the start and end locations of each thread's download data
    For (int startIndex = (if (ID). Start ();}   
    Send request to, request data from start to end position
      "Http://192.168.1.102:8080/editplus.exe";   url url = new URL (path);   HttpURLConnection conn = (httpurlconnection) url.openconnection ();  Conn.setreadtimeout (the);  Conn.setconnecttimeout (conn.setrequestmethod) (//Request partial data Conn.setrequestproperty to the server ("-" + EndIndex); Conn.connect ();     
  • Download the requested data and store it in a temporary file
    if (conn.getresponsecode () = = 206) {
    InputStreamis = Conn.getinputstream (); Randomaccessfile RAF =New Randomaccessfile (GetFileName (path),"RWD");Specifies the location from which to start storing data raf.seek (STARTINDEX);>Byte[] B =new  Byte[1024]; int < Span class= "hljs-string" >len; while ((len = is.read (b))!=-1) {raf.write (B, 0, Span class= "Hljs-keyword" >len); } RAF. close (); 
    }
    Multi-threaded Download with breakpoint continuation
  • Define an int variable to record the total length of data downloaded by each thread, and then add the thread's download start location, and the result is that the next time the thread starts, the result is stored in the cached file
    Used to record the total download length of the current thread  int totals = 0;  while (len = Is.read (b))! = -1) {      raf.write (b,""). GetBytes ()); Raf2. 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
    New FileInputStream (file);    BufferedReader (new InputStreamReader (FIS));  int newstartindex = Integer.parseint (//reads the value as the new starting position startIndex = Newstartindex; Fis.close ();   
  • After all three threads have been downloaded, delete the cache file
    running_thread--;   0) {
    <spanclass="Hljs-keyword" >for (<spanclass= "Hljs-keyword" >int i = <span class= "Hljs-number" >0; I <= <span class= "Hljs-number" > 3; i++) {<span class= "Hljs-keyword" >File f = <span class= "Hljs-keyword" >new <span Span class= "Hljs-keyword" >class= "Hljs-keyword" >file (i + <span class= "hljs-string" > ". txt"); F.<span class= "Hljs-keyword" >delete (); 
    /span>
    }
    Mobile version of the breakpoint continued multi-threaded downloader
  • Just paste the code directly here to use, remember when accessing the file path to change to the Android directory, add access to the network and external storage path with progress bar display download progress (master)
  • Set the maximum value of the progress bar when you get the total length of the download file
    Sets the maximum value of the progress bar  Pb.setmax(length);
  • The progress bar needs to show the overall download progress of three threads, so three threads each time they download, the length of the new download will be added to the progress bar
    Defines an int global variable that records the total download length of three threads '
    int progress;
    Refresh Progress bar
    Is. Read (b))! =-1) {      RAF.  0, Len);  
    Add the length of the current thread's download to the progress bar            Len;            Pb.setprogress (progress);
  • 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.
    New FileInputStream (file);    BufferedReader (new InputStreamReader (FIS));  int newstartindex = Integer.parseint (//Set the downloaded length into the progress bar progress + = Alreadydownload;   
    Add a text box to show percent progress
    Tv.settext"%");

Android Network Programming

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.