Android uses post to submit data (login)

Source: Internet
Author: User

In Android, the standard Java interface httpurlconnection and Apache interface HttpClient are provided, providing rich support for client HTTP programming.

The most used in HTTP communication is get and post, get requests can get static pages, can also put parameters behind the URL string, passed to the server. The difference between post and get is that the post parameter is not placed in the URL string but is placed in the HTTP request data.

This article uses the standard Java interface, HttpURLConnection, to demonstrate how to use post to submit data to the server and display the server's response to the Android client.

1. Server-side Readiness

To complete this example, we need to do the following on the server side:

(1) We need to create a Web project in MyEclipse to emulate the server-side Web service, where I named the project "Myhttp".

(2) Modify the project "index.jsp" file, add two input boxes and a Submit button, as the Web project display page. Running Tomcat, accessing the Web project in a browser, can see the interface shown in 1.

(3) In the Web project, create a Loginaction class that inherits from HttpServlet, and implement the Dopost () method in it to respond to the user action of the page shown in Figure 1. The specific implementation is as follows:

 Public voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); PrintWriter out=Response.getwriter (); String username= Request.getparameter ("username"); String Password= Request.getparameter ("Password"); //determine if the user name password is correct        if(Username.equals ("Admin") && Password.equals ("123")) {             out. Print ("Login succeeded!"); }Else {             out. Print ("Login failed!"); }                 out. Flush ();  out. Close (); }

As can be seen from the above code, when we enter the user name "admin", password "123" in the page shown in Figure 1, click the Submit button, you will get "Login succeeded!" The prompt information for 2 is shown. If the user name, password is wrong, you will get "Login failed!" Prompt for information.

At this point, the server-side readiness is all done.

2. Client implementation

On the Android client, what we need to do is to post the username and password to the above server and get the authentication information of the server.

We do this in a few steps.

2.1 UI Interface

In Android project, we need to complete a simple UI interface, to complete the user name password input, send a POST request, display the server's verification results, completed after the interface 3 is shown.

In mainactivity, we need to get the input of two EditText controls, the listening of the "submit" button, and the TextView content display of the server validation results. The specific implementation code is as follows:

/** Function: Click event response * Author: Blog Park-still indifferent*/     Public voidOnClick (view view) {Switch(View.getid ()) { Caser.id.button_submit:string username=Medittext_username.gettext (). toString (); String Password=Medittext_password.gettext (). toString (); Map<string, string>params=NewHashmap<string, string>(); params. put ("username", username); params. put ("Password", password); Mtextview_result.settext (Httputils.submitpostdata (params,"Utf-8"));  Break; }    }

2.2 Sending a POST request to the server

As you can see in the code above, we call the static method of the Httputils class Submitpostdata () completes sending the POST request to the server and displays the return value of the method (the server's response result) in the TextView control.

In the Httputils class, the specific implementation of the Submitpostdata () method is as follows:

/** Function: Send POST request to server * Param:params request body content, encode encoding format * Author: Blog Park-still indifferent*/     Public StaticString Submitpostdata (map<string, string>params, String encode) {                byte[] data = Getrequestdata (params, encode). ToString (). GetBytes ();//get the request body        Try{httpurlconnection httpurlconnection=(HttpURLConnection) url.openconnection (); Httpurlconnection.setconnecttimeout ( the);//Setting the connection time-out periodHttpurlconnection.setdoinput (true);//Open the input stream to get data from the serverHttpurlconnection.setdooutput (true);//Open the output stream to submit data to the serverHttpurlconnection.setrequestmethod ("POST");//set up post to submit dataHttpurlconnection.setusecaches (false);//cannot use the cache using Post mode//set the type of the request body is the text typeHttpurlconnection.setrequestproperty ("Content-type","application/x-www-form-urlencoded"); //set the length of the request bodyHttpurlconnection.setrequestproperty ("Content-length", String.valueof (data.length)); //get the output stream and write data to the serverOutputStream OutputStream =Httpurlconnection.getoutputstream ();                        Outputstream.write (data); intResponse = Httpurlconnection.getresponsecode ();//get the server's response code            if(Response = =HTTPURLCONNECTION.HTTP_OK) {InputStream Inptstream=Httpurlconnection.getinputstream (); returnDealresponseresult (Inptstream);//processing server Response Results            }        } Catch(IOException e) {e.printstacktrace (); }        return ""; }

As you can see from the code above, there are actually 3 things done in this method:

(1) The user name password is encapsulated into the request body, which is implemented by invoking the Getrequestdata () method (which is described later in this method).

(2) Set various parameters of the HttpURLConnection object (in fact, set the parameters of the HTTP protocol request body), and then obtain the server output stream through the Httpurlconnection.getoutputstream () method OutputStream, and then use the Outputstream.write () method to send the request body content to the server.

(3) Determine the response code of the server, obtain the response input stream of the server through the Httpurlconnection.getinputstream () method, and then call the Dealresponseresult () method to process the server's response results.

2.3 Package Request Body

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

For this instance, the URL request we sent is: http://192.168.1.101:8080/myhttp/servlet/LoginAction, but we need to put the post parameters (also is username and password) encapsulated into the request, form the following form:http://192.168.1.101:8080/myhttp/servlet/loginaction?username=admin& Password=123. What should we do? The following code gives an implementation scenario:

/** Function: Package request body Information * Param:params request body content, encode encoding format * Author: Blog Park-still indifferent*/     Public StaticStringBuffer Getrequestdata (map<string, string>params, String encode) {StringBuffer StringBuffer=NewStringBuffer ();//storage of Packaged request body information        Try {             for(Map.entry<string, string> Entry:params. EntrySet ()) {Stringbuffer.append (Entry.getkey ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), encode)). Append ( /c5>"&"); } Stringbuffer.deletecharat (Stringbuffer.length ()-1);//Delete the Last "&"}Catch(Exception e) {e.printstacktrace (); }        returnStringBuffer; }
/** Function: Processing server response result (convert input stream to string) * Param:inputstream server Response Input stream * Author: Blog Park-still indifferent */     Public Staticstring Dealresponseresult (InputStream inputstream) {string Resultdata=NULL;//Storage Processing ResultsBytearrayoutputstream Bytearrayoutputstream =NewBytearrayoutputstream (); byte[] data =New byte[1024x768]; intLen =0; Try {             while(len = inputstream.read (data))! =-1) {bytearrayoutputstream.write (data,0, Len); }        } Catch(IOException e) {e.printstacktrace (); } resultdata=NewString (Bytearrayoutputstream.tobytearray ()); returnResultdata; }

2.5 Operating Effect

Finally, take a look at how the instance works, as shown in 4.

Android uses post to submit data (login)

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.