Use of the Android Web communication

Source: Internet
Author: User

I. Understanding the fundamentals of Android network

1, Android platform has three kinds of network interface can use

A, standard Java interface java.net.*

B, Apache interface org.apache.* (open source project httpclient)

C, Android network interface android.net.*

Second, Mastering HTTP communication for Android apps

1. HTTP: Hypertext Transfer Protocol (Hyper Text Transfer Protocol)

2. Using Request/Response mode

3. Android provides httpurlconnection and HttpClient interface

Third, HttpURLConnection interface

1, HttpURLConnection is the standard class of Java, inherits from the URLConnection class. They are all abstract classes cannot instantiate an object.

A, mainly through the URL of the OpenConnection method to obtain the creation of the connection, the code is as follows:

New URL ("http://httpurlconnection urlconn = (httpurlconnection) url.openconnection ();

b, the default is to use Get mode, which requires the URL to pass parameters can be

URL url=new URL ("Http:www.google.com?parameter=bruce"); HttpURLConnection urlconn= (httpurlconnection) url.openconnection ();

C, using the Post method, you need Setrequestmethod settings

//Set the post modeUrlconn.setrequestmethod ("POST");//Setting the connection time-out, in millisecondsUrlconn.setconnecttimeout (10*1000);//set read time-out, in millisecondsUrlconn.setreadtimeout (15*1000);//sets whether to allow receiving server-side response content, by default trueUrlconn.setdoinput (true);//sets whether to allow the building of an output flow to the server to pass data, false by defaultUrlconn.setdooutput (true);//set whether to use cache, post cannot use cacheUrlconn.usecache (false);//Establish a connectionUrlconn.connect ();

D, access to the network image, only need to convert the resulting data flow to bitmap on it.

Create HttpURLConnection
HttpURLConnection conn=(httpurlconnection) iamgeurl.openconnection ();
Sets whether to allow receiving server-side response content (by default, True) Conn.setdoinput (
true);
Establish connection conn.connect ();
Build the input stream InputStream stream
=conn.getinputstream ();
Convert data flow to Bitmapbitmap
=Bitmapfactory.decodestream (stream);
Close flow is.close ();

Iv. HttpClient

The httpclient provided by Apache is also suitable for us to develop Internet applications on Android

1. Clientconnectionmanager interface

A, interface for client connection management

2, Defaulthttpclient

A, the default HTTP client, you can use to create an HTTP connection

3, HttpResponse

A, an HTTP connection response, through which you can get the response message returned

Ii. Steps of implementation

1, the use of httpclient requires the following five steps;

A, instantiate the HttpClient object with Defaulthttpclient.

B. Create a HttpGet or HttpPost object, and the URL to be requested is passed through the constructor method to the HttpGet or HttpPost object.

C. Call the Execute method to send an HTTP GET or HTTP POST request and return the HttpResponse object.

D, the response information is returned through the GetEntity method of the HttpResponse interface and processed accordingly.

E, release the connection. The connection must be released regardless of the success of the execution method.

2. Submit request using Get method

// HttpGet Connection Object New HttpGet (httpurl); // Get HttpClient Object New defaulthttpclient (); // request HttpClient, get HttpResponse HttpResponse HttpResponse = Httpclient.execute (HttpRequest);

3. Determine if the request was successful based on the code in response

// Request succeeded if (Httpresponse.getstatusline (). Getstatuscode () = = Httpstatus.sc_ok) {}

4. Code (GET)

//building an instance of HttpClientDefaulthttpclient httpclient=Newdefaulthttpclient ();//Create a Get instanceHttpGet get=NewHttpGet ("http://www.baidu.com");Try{    //send request and get response resultHttpResponse res=Httpclient.execute (GET); //processing response result Data    if(Res! =NULL&& res.getstatusline (). Getstatuscode () = =HTTPSTAATUS.SC_OK)    {System.out.println (entityutils.tostring (Res.getemtity ())); } }Catch(Exception ex) {ex.printstacktrace (); }finally{      //Freeing ResourcesHttpclient.getconnectionmanager (). shutdown ();} 

5. Submit the request using Post

// HttpPost Connection Object HttpPost httprequest=New httppost (Httpurl);

6. Use Namevaluepair to save the parameters to be passed

// use Namevaluepair to save the post parameters to be passed list<namevaluepair>params=New arraylist<namevaluepair>(); // Add the parameters to be passed Params.add (new Basicnamevaluepair ("Pair", "httpclient_android_post"));

7. Request is also submitted via HTTP client

// Set character sets Httpentity httpentity=New urlencodedformentity (params, "utf-8"); // Request HttpRequest httprequest.setentity (httpentity); // get the default httpclient HttpClient httpclient=New  defaulthttpclient (); // Submit Request Httpclient.execute (HttpRequest);

8. Post Code

//Building HttpClient InstancesDefaulthttpclient httpClient =Newdefaulthttpclient ();//Create a Post instanceHttpPost post =NewHttpPost ("http://www.baidu.com")//Initializing Request Parameterslist<namevaluepair> params =NewArraylist<namevaluepair>();p Arams.add (NewBasicnamevaluepair ("Stuno", "123456"));p Arams.add (NewBasicnamevaluepair ("Stuname", "Zhangsan"));p Arams.add (NewBasicnamevaluepair ("Stusex", "male"));p Arams.add (NewBasicnamevaluepair ("Stutemp", "1997-1-1"));p Arams.add (NewBasicnamevaluepair ("Stuaddress", "Zhuhai"));Try{     //set the request parameters and encode them in UTF-8 modePost.setentity (NewUrlencodedformentity (params, "UTF-8")); //send request and get response resultHttpResponse res=Httpclient.execute (POST); //processing response result Data     if(Res! =NULL&& res.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK)       {System.out.println (entityutils.tostring (Res.getentity ())); }}Catch(Exception ex) {ex.printstacktrace (); }finally{      //Freeing ResourcesHttpclient.getconnectionmanager (). shutdown ();}

9, real-time updates can be in the client through the thread does not listen to the request and refresh the page

10, can not directly update the UI in the thread, need to use handler to implement, the code is as follows:

Handler mhandler=New  Handler () {  publicvoid  handlemessage (Message msg) {       Super . Handlemessage (msg);       // Refresh       Refresh ();    }  }

Use of the Android Web 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.