Android network communication

Source: Internet
Author: User

1. HttpURLConnection interface      First of all it needs to be clear that the way the post and get requests are different in HTTP communication. Get can get a static page, or you can put parameters behind the URL string and pass it to the server. The parameters of the Post method are placed in the HTTP request. Therefore, before programming, you should first explicitly use the request method, and then choose the appropriate programming mode according to the way you use it.     httpurlconnection is inherited from the URLConnection class, both of which are abstract classes. Its object is obtained mainly through the OpenConnection method of URL. The creation method is shown in the following code:   1.url url = new URL ("http://www.51cto.com/");  2.httpurlconnection urlconn= (httpurlconnection) url.openconnection ();      You can set the properties of the request in the following ways, as follows: 1.//set input and output stream  2.urlconn.setdooutput (true);  3.urlconn.setdoinput (TRUE);  4.//Set Request mode is post  5.urlconn.setrequestmethod ("POST");  6.//post request cannot use cache  7.urlconn.setusecaches (false);  8.//Close Connection  9.urlconn.disconnection ();  10.  httpurlconnection uses the Get method by default, as shown in the following code:  1.string httpurl= "http://192.168.1.110:8080/ HTTPGET.JSP?PAR=ABCDEFG '; 2.URL url=new URL (httpurl); 3.//use httpurlconnection to open connection  4.            &nbsP;   httpurlconnection urlconn = (httpurlconnection) url.openconnection ();  5.                //Gets the content read (stream)  6.                inputstreamreader  in = new InputStreamReader (Urlconn.getinputstream ());  7.                // Create BufferedReader  8 for the output.                bufferedreader Buffer = new BufferedReader (in);   9.                string inputLine = null ;  10.                //using loops to read the data obtained   One.                while ((Inputline = Buffer.readline ()) = null))  12.                { 13.                     // We'll add a "\ n" to the line after each line to wrap the  14.                     resultdata + = Inputline + "\ n";  15.                }            16.                // Close the InputStreamReader  17.                in.close ();  18.                //close the HTTP connection  19.        &nBsp;       urlconn.disconnect ();       If you need to use post, the Setrequestmethod setting is required. The code is as follows:   1.string Httpurl = "http://192.168.1.110:8080/httpget.jsp";  2.        //data obtained by  3.        string resultdata = "";  4.        url URL = null;  5.        try 6.        { 7.             //constructs a URL object  8.            url = new URL (httpurl);   9.        }  10.        catch (malformedurlexception e)  11.        { 12.             LOG.E (Debug_tag,"Malformedurlexception");  13.        }  14.        if (URL! = null)  15.        { 16.             try 17.            { 18.                 //use HttpURLConnection to open the connection  19.                httpurlconnection Urlconn = (httpurlconnection) url.openconnection ();   20.                //because this is a POST request, Set the required setting to True  21.                urlconn.setdooutput ( true);  22.             &nbSp;  urlconn.setdoinput (TRUE);  23. The                //setting is  24 post.                 Urlconn.setrequestmethod ("POST");  25.                //Post Request cannot use cache                   Urlconn.setusecaches (FALSE);  27.                 Urlconn.setinstancefollowredirects (TRUE);  28.                // Configure the Content-type for this connection, configured as Application/x-www-form-urlencoded  29.                 Urlconn.setrequestproperty ("Content-type", "Application/x-www-foRm-urlencoded ");  30.                //Connection, The configuration from Posturl.openconnection () to this point must be completed before connect,  31.                // It is important to note that Connection.getoutputstream will implicitly connect.  32.                urlconn.connect ();  33.                //dataoutputstream Flow  34.                dataoutputstream out = New DataOutputStream (Urlconn.getoutputstream ());  35.                //the parameter  36 to upload.                string content = "Par=" + urlencoder.encode ("ABCDEFG", "gb2312 ");  37.                //the content to be uploaded is written to the stream                  out.writebytes ( content);   39.                //refresh, close  40.                out.flush ();  41.                out.close ();   2. HttpClient Interface      HTTP operation is also possible using the HttpClient interface provided by Apache.      the operations for the Get and post request methods are different. An example of the action code for the Get method is as follows:  1.//HTTP address  2.        string Httpurl = "Http://192.168.1.110:8080/httpget.jsp?par=HttpClient_ Android_get ";  3.        //httpget the Connection object  4.      &nbsP; httpget HttpRequest = new HttpGet (Httpurl);  5.         //get HttpClient object  6.            httpclient HttpClient = new DefaultHttpClient ();  7.            //request HttpClient, get HttpResponse  8.            httpresponse HttpResponse = Httpclient.execute ( HttpRequest);  9.            //request succeeded  10.            if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK)  11.            { 12.                 //gets the returned string  13.              &nbsP; string strresult = entityutils.tostring (Httpresponse.getentity ());  14.                mtextview.settext ( Strresult);  15.            }  16.            else 17.            { 18.                 mtextview.settext ("Request error!");  19.            }  20.        }       when using the Post method for parameter passing, You need to use Namevaluepair to save the arguments you want to pass. , you also need to set the character set you are using. The code looks like this:   1.//http address  2.        string Httpurl = "http://192.168.1.110:8080/httpget.jsp";  3.        //httppost connection toLike  4.        httppost HttpRequest = new HttpPost (Httpurl);  5.        //uses Namevaluepair to save the post parameter  6 to be passed.        list params = new ArrayList ();  7.        //Add the parameter  8 to be passed.        params.add (New Basicnamevaluepair ("par", "httpclient_android_post"));  9.        //sets the character set  10.            httpentity HttpEntity = new UrlEncodedFormEntity (Params, "gb2312");  11.            //Request HttpRequest  12.            httprequest.setentity (httpentity);  13.            //Gets the default HttpClient  14.        &nBsp;   httpclient HttpClient = new Defaulthttpclient ();  15.            //obtained HttpResponse  16.            httpresponse HttpResponse = Httpclient.execute ( HttpRequest);  17.            //HTTPSTATUS.SC_OK indicates a successful connection  18.            if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK)  19.            { 20.                 //gets the returned string  21.                string StrResult = Entityutils.tostring (Httpresponse.getentity ());  22.               &nBsp;mtextview.settext (strresult);  23.            }  24.            else 25.            { 26.                 mtextview.settext ("Request error!");  27.            }  28.        }      httpclient is actually some encapsulation of Java-provided methods, The input-output stream operation in HttpURLConnection is uniformly encapsulated in this interface as HttpPost (HttpGet) and HttpResponse, thus reducing the complexity of the operation.       In addition, character encoding is required when transmitting using post.

Android network communication

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.