Several ways to operate the Android network

Source: Internet
Author: User

Android Development software: Androidstudio

Server Software: Myeclipse+tomcat

First of all, regardless of the way, Android mobile phone software to network, you must apply for Internet access (Android.permission.INTERNET).

The Android main thread does not allow time-consuming operations (the networking operation is a time-consuming operation), so the following network operations are operated by one thread from the internal anonymous class .

One, the first way: using HttpURLConnection for networked operations

This method requires us to manually build an HTTP request package that is sent to the specified server

  1. Get mode
    1. Set URL
    2. Open connection
    3. Set the request method to get
    4. Setting the connection time-out period
    5. Set the Read timeout time
    6. Send the current request to the server side
    7. Waiting for a response from the server (blocked here)
    8. Get the response code (and do the corresponding action in the response code), because UI updates are not allowed within the Androzo thread, so you need to go to the main thread (via handler in Android to pass the message to the main thread)
       Public voidGetpic (View v) {NewThread (NewRunnable () {@Override Public voidrun () {Try {                    //the first place to spend the server's addressURL url=NewURL ("Http://192.168.2.1/day10_NetworkServer/brushli.jpg"); //Connect via HTTPHttpURLConnection httpurlconnection =(HttpURLConnection) url.openconnection (); //set the request mode and set the wait response timeHttpurlconnection.setrequestmethod ("GET"); Httpurlconnection.setconnecttimeout (5000); //send the current request to the server (Android does not allow time-consuming operations within the main thread, such as connecting to a server)Httpurlconnection.connect (); //wait for the operation after sending the connection, this is a blocking method,                    intResponsecode =Httpurlconnection.getresponsecode (); //according to the resulting response code and response information to make the appropriate action                    if(responsecode==200){                        //read information from the server correctly or notInputStream is=Httpurlconnection.getinputstream (); File File=NewFile ("/data/data/com.rgd.day10_network_3/files");                        File.mkdir (); FileOutputStream Fos=NewFileOutputStream (NewFile ("/data/data/com.rgd.day10_network_3/files/brushli.jpg")); byte[] buffer=New byte[1024]; intRead;  while(Read =is.read (buffer))!=-1) {fos.write (buffer,0, read); }                        //because child threads do not allow UI update operations to be performed with the main thread through handlerMessage msg=NewMessage (); Msg.what=1;                        Handler.sendmessage (msg);                        Fos.close ();                    Is.close (); }                } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace ();    }}). Start (); }handler Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Switch(msg.what) { Case1: Toast.maketext (mainactivity. This, "Save picture succeeded", Toast.length_long). Show ();  Break;  Case2: Toast.maketext (mainactivity. This, "Save MP3 Success", Toast.length_long). Show ();  Break;  Case3: Toast.maketext (mainactivity. This, "Save video Success", Toast.length_short). Show (); default:                     Break; }        }    };
      View Code   

2.Post mode  

    • Operations are similar to get, except that post delivery information is passed through the body, and get is placed in the connection
    • NewThread (NewRunnable () {@Override Public voidrun () {Try {                        //the first place to spend the server's addressURL url=NewURL ("Http://192.168.106.1/day10_NetworkServer/servlet/loginInfo"); //Connect via HTTPHttpURLConnection httpurlconnection =(HttpURLConnection) url.openconnection (); //set the request mode and set the wait response timeHttpurlconnection.setrequestmethod ("POST"); Httpurlconnection.setconnecttimeout (5000); String Data= "Username=" +username+ "&password=" +password+ "&email=" +email+ "&phonenumber=" +PhoneNumber; OutputStream OutputStream=Httpurlconnection.getoutputstream ();                        Outputstream.write (Data.getbytes ()); //send the current request to the server (Android does not allow time-consuming operations within the main thread, such as connecting to a server)Httpurlconnection.connect (); //wait for the operation after sending the connection, this is a blocking method,                        intResponsecode =Httpurlconnection.getresponsecode (); //according to the resulting response code and response information to make the appropriate action                        if(responsecode==200){                            //read information from the server correctly or notInputStream is=Httpurlconnection.getinputstream (); byte[] buffer=New byte[1024]; intRead =is.read (buffer); String result=NewString (buffer,0, read); //because child threads do not allow UI update operations to be performed with the main thread through handlerMessage msg=NewMessage (); Msg.what=1;                        Handler.sendmessage (msg); }Else{Message msg=NewMessage (); Msg.what=-1;                        Handler.sendmessage (msg); }                    } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }}). Start ();
      View Code

3. By

      

Several ways to operate the Android network

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.