Android study note 46: submit data using post

Source: Internet
Author: User
Tags response code

In Android, the standard Java interface httpurlconnection and Apache interface httpclient are provided, which provides rich support for HTTP programming on the client.

Get and post are the most commonly used in HTTP Communication. GET requests can obtain static pages, or they can place parameters after URL strings and pass them to the server. The difference between post and get is that the post parameter is not placed in the URL string, but in the HTTP request data.

This article uses the standard Java interface httpurlconnection to demonstrate how to use the post method to submit data to the server with an instance, and display the server response results on the android client.

 

1. Server preparation

To complete the instance, we need to make the following preparations on the server:

(1) We need to create a web project in myeclipse to simulate the Web service on the server. Here, I name this project "myhttp ".

(2) modify the "index. jsp" file of the project and add two input boxes and a submit button as the web project display page. Run Tomcat and access the Web project in the browser. The interface shown in 1 is displayed.

Figure 1 WEB Project display page

(3) In this web project, create a loginaction class inherited from httpservlet and implement the dopost () method to respond to user operations on the page shown in Figure 1. The specific implementation is as follows:

 1  Public   Void  Dopost (httpservletrequest request, httpservletresponse response)  2               Throws  Servletexception, ioexception {  3  4 Response. setcontenttype ("text/html; charset = UTF-8" );  5 Request. setcharacterencoding ("UTF-8" );  6 Response. setcharacterencoding ("UTF-8" );  7 Printwriter out = Response. getwriter ();  8           9 String username = request. getparameter ("username" );  10 String Password = request. getparameter ("password" );  11                   12           //  Determine whether the user name and password are correct  13           If (Username. Equals ("admin") & password. Equals ("123" )){  14 Out. Print ("Login Succeeded! " );  15 } Else  {  16 Out. Print ("Login Failed! " );  17   }  18           19   Out. Flush ();  20   Out. Close ();  21 }

ByCodeAs you can see, when we enter the username "admin" and password "123" on the page shown in figure 1, click Submit to get "Login Succeeded !" 2. If the user name and password are incorrect, the system will get "Login Failed !" .

Figure 2 logon success page

Now, all the preparations for the server are complete.

 

2. Client implementation

On the android client, we need to do the following: Send the username and password to the above server in post mode and obtain the server verification information.

Follow these steps.

2.1 UI

In the android project, we need to complete a simple UI interface for entering the user name and password, sending post requests, and displaying the server's verification results, as shown in Interface 3 after completion.

Figure 3 client UI

In mainactivity, we need to obtain the input of two edittext controls, the "Submit" button listening, and the textview content of the server verification result. 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 Mtextview_result.settext (httputils. submitpostdata (Params, "UTF-8" ));  14               Break  ;  15   }  16 }

2.2 send a POST request to the server

We can see that in the above Code, we call the static method of the httputils class submitpostdata () to complete the POST request to the server, and return the value of this method (the server response result) displayed in the textview control.

In the httputils class, the implementation of the submitpostdata () method is as follows:

 /* * Function: Send a POST request to the server * Param: Params Request body content. The encode encoding format is * Author: blog-still indifferent  */      Public   Static String submitpostdata (Map <string, string> Params, string encode ){  Byte [] DATA = getrequestdata (Params, encode). tostring (). getbytes (); //  GET Request body          Try  {Httpurlconnection =(Httpurlconnection) URL. openconnection (); httpurlconnection. setconnecttimeout ( 3000 ); //  Set connection timeout Httpurlconnection. setdoinput ( True ); //  Open the input stream to obtain data from the server Httpurlconnection. setdooutput ( True ); //  Open the output stream to submit data to the server Httpurlconnection. setrequestmethod ("Post "); // Set to submit data in post Mode Httpurlconnection. setusecaches ( False ); //  Cache cannot be used when post is used  //  Set the Request body type to text Httpurlconnection. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded" );  //  Set the length of the Request body Httpurlconnection. setrequestproperty ("Content-Length" , String. valueof (data. Length ));  // Obtain the output stream and write data to the server Outputstream = Httpurlconnection. getoutputstream (); outputstream. Write (data );  Int Response = httpurlconnection. getresponsecode (); //  Obtain the server response code              If (Response = Httpurlconnection. http_ OK) {inputstream inptstream = Httpurlconnection. getinputstream ();  Return Dealresponseresult (inptstream );//  Processing Server Response Results  }}  Catch  (Ioexception e) {e. printstacktrace ();}  Return "" ;} 

The code above shows that three things are actually completed in this method:

(1) encapsulate the user name and password into the Request body. This is achieved by calling the getrequestdata () method (the specific implementation of this method will be discussed later ).

(2) set various parameters of the httpurlconnection object (in fact, the parameters of the HTTP Request body), and then use httpurlconnection. the getoutputstream () method obtains the output stream outputstream of the server, and then uses outputstream. the write () method sends the Request body to the server.

(3) determine the server response code, obtain the server response input stream through the httpurlconnection. getinputstream () method, and then call the dealresponseresult () method to process the server response results.

2.3 encapsulate the Request body

When a POST request is used, the post parameter is not placed in the URL string, but in the HTTP request data. Therefore, we need to encapsulate the post parameter.

For this instance, the URL request we send is: http: // 192.168.1.101: 8080/myhttp/servlet/loginaction, but we need to set the post parameter (that is, username and password) encapsulate the request in the following form: http: // 192.168.1.101: 8080/myhttp/servlet/loginaction? Username = Admin & Password = 123. What should we do? The following code provides an implementation scheme:

 1       /*  2   * Function: encapsulate the Request body information.  3  * Param: the content of the Params Request body, in the encode encoding format.  4   * Author: blog Park-still indifferent  5        */  6       Public   Static Stringbuffer getrequestdata (Map <string, string> Partams, string encode ){  7 Stringbuffer = New Stringbuffer (); //  Store encapsulated Request body information 8           Try  {  9               For (Map. Entry <string, string> Entry: Params. entryset ()){  10   Stringbuffer. append (entry. getkey ())  11 . Append ("=" )  12   . Append (urlencoder. encode (entry. getvalue (), encode ))  13 . Append ("&" );  14   }  15 Stringbuffer. deletecharat (stringbuffer. Length ()-1 ); //  Delete the last "&"  16 } Catch  (Exception e ){  17   E. printstacktrace ();  18   }  19          Return  Stringbuffer;  20 }

2.4 Process Response Results

Finally, let's take a look at how the server returns results. In this instance, the server returns the string "Login Succeeded !" Or "Login Failed !", So what we need to do here is to convert the server return result input into a string. Of course, if the server returns an image, we need to transfer the input to a bitmap image. The following code is the specific implementation of the dealresponseresult () method used in the above Code.

 1       /*  2   * Function: Process Server Response Results (convert input into strings)  3   * Param: Response input stream of the inputstream Server  4  * Author: blog Park-still indifferent  5        */  6       Public   Static  String dealresponseresult (inputstream ){  7 String resultdata = Null ; //  Storage processing result  8 Bytearrayoutputstream = New  Bytearrayoutputstream (); 9           Byte [] DATA = New   Byte [1024 ];  10           Int Len = 0 ;  11           Try  {  12               While (LEN = inputstream. Read (data ))! =-1 ){  13 Bytearrayoutputstream. Write (data, 0, Len );  14   }  15 } Catch  (Ioexception e ){  16   E. printstacktrace ();  17   }  18 Resultdata = New  String (bytearrayoutputstream. tobytearray ());  19           Return Resultdata;  20 }

2.5 Running Effect

Finally, let's take a look at the running effect of the instance, as shown in figure 4.

Figure 4 instance running effect

 

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.