Android study note 47: using the httpclient interface for network communication

Source: Internet
Author: User

In Android, we can use standard Java interfaces to complete Android applications.Program. However, in actual development, more complex online operations may be required. Therefore, the Android platform provides the Apache httpclient interface, it provides efficient, convenient, and function-rich toolkit support for HTTP programming on the client.

While introducing Apache httpclient, the Android platform also encapsulates and extends it, such as setting the default HTTP timeout and cache size. Using the Apache httpclient interface, we can create httpclient, httpget/httppost, httpresponse, and other objects, set connection parameters, perform HTTP operations, and process server return results.

This article uses two examples to demonstrate how to use the httpclient interface in Android development to complete client HTTP programming. One instance uses the get method to obtain images from the server for display, and one instance uses the POST method to submit data to the server to complete the login function.

 

1. common interfaces and Classes

Before explaining the instance, we need to know which common interfaces and classes are provided in the httpclient interface.

1.1 clientconnectionmanager Interface

Clientconnectionmanager is a Client Connection Manager interface used to manage clients connected to the server. It mainly provides the following six Abstract METHODS:

(1) Abstract void closeexpiredconnections ();

(2) Abstract void closeidleconnections (long idletime, timeunit tunit );

(3) Abstract schemeregistry getschemeregistry ();

(4) Abstract void releaseconnection (managedclientconnection Conn, long validduration, timeunit );

(5) Abstract clientconnectionrequest requestconnection (httproute route, object State );

(6) Abstract void Shutdown ();

The closeexpiredconnections () method is used to close all expired connections. The closeidleconnections () method is used to close all idle connections. The getschemeregistry () method is used to obtain the registration scheme. releaseconnection () the method is used to release the connection. The requestconnection () method is used to request a new connection. The shutdown () method is used to close the manager and release resources.

1.2 defaulthttpclient

Defaulthttpclient is a direct subclass of the httpclient interface. It is a default HTTP client and can be used to create an HTTP connection. Multiple overloaded execute () methods are provided in the httpclient interface to execute HTTP requests.

1.3 httprequest Interface

Both httpget and httppost are directly subclasses of the httprequest interface, which are used to submit GET requests and post requests to the server respectively.

1.4 httpresponse Interface

The httpresponse interface provides HTTP response information, as shown in method 1.

Figure 1 main methods provided by the httpresponse Interface

The getentity () method is used to obtain the message entity of the response. The getstatusline () method is used to obtain the status row of the response. The returned statusline object contains the status code of the HTTP response, you can use getstatuscode () to obtain it.

 

2. Get images on the server using get

In this example, we used the web project built in the previous blog "android study note 46: using the postfang documentation as a server, and included a picture named “cat.jpg in the project as the object we will get.

To obtain images on the server using get, follow these four steps:

(1) create a get httprequest request object.

(2) create a default HTTP client and execute the HTTP request in this get method.

(3) obtain the server response code and determine whether the server responds correctly.

(4) obtain the server response content (inputstream) and convert it to a bitmap image.

Implementation of the above four stepsCodeAs follows:

 1       /*  2   * Function: Send a GET request.  3   * Author: blog Park-still indifferent  4        */  5       Public   Static Bitmap sendgetresquest (string path ){  6 Bitmap bitmap = Null  ;  7 Httpget = New Httpget (PATH ); //  Create an httprequest object in get Mode  8 Defaulthttpclient httpclient = New Defaulthttpclient (); //  Create a default HTTP client  9          Try  {  10 Httpresponse = httpclient.exe cute (httpget ); //  Execute HTTP requests in get Mode  11               Int Reponsecode = httpresponse. getstatusline (). getstatuscode (); //  Obtain the server response code  12               If (Reponsecode = Httpstatus. SC _ OK ){  13 Inputstream = httpresponse. getentity (). getcontent (); //  Obtain the server response content  14 Bitmap = Bitmapfactory. decodestream (inputstream );  15   Inputstream. Close ();  16   }  17 } Catch  (Clientprotocolexception e ){  18  E. printstacktrace ();  19 } Catch  (Ioexception e ){  20   E. printstacktrace ();  21   }  22           Return  Bitmap;  23 }

Finally, we use a button in the activity to send a GET request to the server and call the sendgetresquest () method to display the obtained bitmap object in the imageview control. The specific implementation code is as follows:

 1      /*  2   * Function: Click Event Response.  3   * Author: blog Park-still indifferent  4        */  5       Public   Void  Onclick (view ){  6           Switch  (View. GETID ()){  7           Case R. Id. button_get:  8 String url = "http: // 192.168.1.101: 8080/myhttp/cat.jpg" ;  9 Bitmap bitmap = Httputils. sendgetresquest (URL );  10   Mimageview. setimagebitmap (Bitmap );  11               Break  ;  12   }  13 }

Run the project and click "Submit GET request". The page shown in Figure 2 is displayed, the image shown below the "Submit GET request" button is the image we get from the server.

Figure2UseGetMethod to retrieve images on the server

 

3. Use the POST method to submit data to the server

In this example, we also used the web project created in the previous blog "android study note 46: submit data using post" as a server. Run Tomcat and access the Web project in the browser. The page shown in 3 is displayed.

Figure 3 web project display page

The instance must submit the user name and password to the server in post mode, simulate the logon process, and obtain the server verification information to check whether the logon is successful.

Using the POST method to submit data to the server is a little more complex than the get method. You can follow the five steps below:

(1) encapsulate the Request body parameters (username and password.

(2) create a post-based httprequest object and set the post-based Request body.

(3) create a default HTTP client and execute the HTTP request in this post mode.

(4) obtain the server response code and determine whether the server responds correctly.

(5) obtain the server response content (inputstream) and convert it to a string for display.

The specific implementation code of the above five steps is as follows:

 1       /* 2   * Function: Send a POST request.  3   * Author: blog Park-still indifferent  4        */  5       Public   Static String sendpostresquest (string path, Map <string, string> Params, string encoding ){  6 List <namevaluepair> List = New Arraylist <namevaluepair> (); // Encapsulate Request body parameters  7           If (Params! = Null )&&! Params. isempty ()){  8               For (Map. Entry <string, string> Param: Params. entryset ()){  9 List. Add ( New  Basicnamevaluepair (Param. getkey (), Param. getvalue ()));  10   } 11   }  12           Try  {  13 Urlencodedformentity entity = New Urlencodedformentity (list, encoding ); //  URL encoding of Request body parameters  14 Httppost = New Httppost (PATH ); //  Create a post-based httprequest object  15 Httppost. setentity (entity ); //  Set the POST Request body  16 Defaulthttpclient client = New  Defaulthttpclient ();  17 Httpresponse = client.exe cute (httppost ); //  Execute POST request  18               Int Reponsecode = httpresponse. getstatusline (). getstatuscode (); //  Obtain the server response code 19               If (Reponsecode = Httpstatus. SC _ OK ){  20 String resultdata = entityutils. tostring (httpresponse. getentity ()); //  Obtain the server response content  21                   Return  Resultdata;  22   }  23 } Catch  (Ioexception e ){ 24   E. printstacktrace ();  25   }  26           Return "" ;  27 }

Similarly, we use a button in the activity to send a POST request to the server and call the sendpostresquest () method to display the server response results in the textview control. The specific implementation code is as follows:

 1       /*  2   * Function: Click Event Response.  3  * Author: blog Park-still indifferent  4        */  5       Public   Void  Onclick (view ){  6           Switch  (View. GETID ()){  7           Case  R. Id. button_submit:  8 String username = Medittext_username.gettext (). tostring (); 9 String Password = Medittext_password.gettext (). tostring ();  10 Map <string, string> Params = New Hashmap <string, string> ();  11 Params. Put ("username" , Username );  12 Params. Put ("password" , Password );  13 String url = "http: // 192.168.1.101: 8080/myhttp/servlet/loginaction" ; 14 Mtextview_result.settext (httputils. sendpostresquest (URL, Params, "UTF-8" ));  15               Break  ;  16   }  17 }

Run the project, enter the username and password in the edittext control, and click "submit data". The displayed page shown in Figure 4 is displayed, in the textview control under the "submit data" button, the server returns "Login Succeeded!" .

 

Related Article

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.