Get-post login request for Android

Source: Internet
Author: User

1. Case: Two Methods of logon and request parameter submission

Webpage User Logon: JSP (client) + servlet (server)

Android User Logon: Android (client) + servlet (server)

Technologies used by Web client:
It is easy to send a connection request on a webpage. After the Request Path is set, the browser automatically sends the request. You only need to specify method = "Get/Post ".

Technologies used by Android clients:
Android must manually send a connection request. The steps are as follows, and get and post are different.
GET request login:

1. Prepare the Request Path and request parameter string
String Path = "http: // 192.168.1.10/login/loginservlet? Name = ABC & Password = 123 ";
Because the browser will automatically encode the Chinese request parameters, such as the following format: % DE3 % ADF, in order to enable the server to receive data
Encode Chinese parameters without garbled characters. The format is as follows:
Name = urlencoder. encode (name );

2. Package the request URL
URL url = new URL (PATH)

3. Create a request connection object
Httpurlconnection conn = (httpurlconnection) URL. openconnection ();

4. Set the connection mode (and send a request) and connection timeout period
Conn. setrequestmethod ("get ");
Conn. setconnectiontimeout (5000 );
5. Receive Request Response codes and Response Data
If (conn. getresponsecode = 200 ){
Inputstream is = conn. getinputstream ();
Byte [] DATA = streamtools. getbytes (is );
/* Streamtools is a tool class that stores data in the input stream in the byte buffer array bytearraystream,
The length of the array can be changed too much, because if you store the array directly, you do not know the size of the new array,
Assign a value to the array when declaring it directly. You do not need to specify the length of the array.
*/
String result = new string (data );
}

Post login request: Because the POST method directly writes data to the server through a stream, there are more steps:
1. Set the request path string (without request parameters)
String Path = "http: // 192.168.1.10/login/loginservlet ";

2. Package the request URL
URL url = new URL (PATH );

3. Create a connection
Httpurlconnection conn = (httpurlconnection) Ur. openconnection ();

4. Set the connection mode and connection timeout period
Conn. setrequestmethod ("Post ");
Conn. setconnectiontimeout (5000 );

5. Prepare the data to be sent.
String data = "name =" + urlencoder. encode (name) + "Password =" + urlencoder. encode (password );

6. Set the Content-Type and Content-Length headers required for get.

Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded ");
Conn. setrequestproperty ("conent-length", Data. Length () + "");

7. Tell the urlconnection whether it is input or output.
URL connections can be used for input and/or output.
If you want to use a URL Connection for output, set the dooutput flag to true. If you do not want to use it, set it
False. The default value is false;
If you want to use a URL Connection for input, set the doinput flag to true. If you do not want to use it, set it
False. The default value is true.
Conn. setdooutput (true );

8. Create a conn output stream
Outputstream OS = conn. getoutputstream ();

9. Output content
OS. Write (data. getbytes ());

10. Receive Request Response codes and Response Data
If (conn. getresponsecode = 200 ){
Inputstream is = conn. getinputstream ();
Byte [] DATA = streamtools. getbytes (is );
/* Streamtools is a tool class that stores data in the input stream in the byte buffer array bytearraystream,
The length of the array can be changed too much, because if you store the array directly, you do not know the size of the new array,
Assign a value to the array when declaring it directly. You do not need to specify the length of the array.
*/
String result = new string (data );
}
<! ######################################## ######################################## ################!>

Httpclient: equivalent to simulating the browser access process.
1. Open a browser
2. Prepare data
3. Press enter to send a request and receive a response.
Httpget Logon:

1. Open a browser (create httpclient)
Httpclient client = new defaulthttpclient ();

2. Prepare the data and create a GET request address bar.
String name = urlencoder. encode (name );
String Path = "http: // 192.168.1.10/login/loginsevlet? Name = "+ name +" Password = "+ password;
Httpget = new httpget (PATH );

3. Press enter to send a request and receive a response.
Httpresponse response = client.exe cute (httpget );
Int code = response. getstatusline (). getstatuscode ();
If (code = 200 ){
Inputstream is = response. getentity (). getcontent ();
String result = new string (streamtools. getbytes (is ));
}

Httppost Logon: (simulated)
1. Open a browser
Httpclient client = new defaulthttpclient ();

2. Prepare the data and create a POST request address bar.
String Path = "http: // 192.168.1.10/login/loginservlet"; // request address
List <namevaluepair> parameters = new arraylist <namevaluepair> (); // request data (instead of the output stream)
Parameters. Add (New basicnamevaluepair ("name", name );
Parameters. Add (New basicnamevaluepair ("password", password );

Httppost = new httppost (PATH );
Httppost. setentity (New urlencodedformentity (parameters, "UTF-8 ");

3. Press enter to send a request and receive a response.
Httpresponse response = client.exe cute (httppost );
Int code response. getstatusline (). getstatuscode ();
If (code = 200 ){
Inputstream is = response. getentity (). getcontent ();
String result = new string (streamtools. getbytes (is ));
}

Example:

Use httpget and httppost to access HTTP resources

Requirement: User Logon (Name: User Name, PWD: password)

(1) httpget: doget () method

// Doget (): attaches the key-value pair of the parameter to the end of the URL for transmission.

Public String getresultforhttpget (string name, string PWD) throws clientprotocolexception, ioexception {

// Server: server project: servlet name

String Path = "http: // 192.168.5.21: 8080/test ";

String uri = path + "? Name = "+ name +" & Pwd = "+ PWD;

// Name: the username of the server, PWD: the password of the server

// Note that the string connection cannot contain spaces



String result = "";



Httpget = new httpget (URI );

Httpresponse response = new defaulthttpclient(cmd.exe cute (httpget );

If (response. getstatusline (). getstatuscode () = 200 ){

Httpentity entity = response. getentity ();

Result = entityutils. tostring (entity, HTTP. utf_8 );

}

Return result;

}

(2) httppost: dopost () method

// Dopost (): Package the parameters into the HTTP header for transmission.

Public String getreultforhttppost (string name, string PWD) throws clientprotocolexception, ioexception {

// Server: server project: servlet name

String Path = "http: // 192.168.5.21: 8080/test ";

Httppost = new httppost (PATH );

List <namevaluepair> List = new arraylist <namevaluepair> ();

List. Add (New basicnamevaluepair ("name", name ));

List. Add (New basicnamevaluepair ("PWD", PWD ));

Httppost. setentity (New urlencodedformentity (list, HTTP. utf_8 ));



String result = "";



Httpresponse response = new defaulthttpclient(cmd.exe cute (httppost );

If (response. getstatusline (). getstatuscode () = 200 ){

Httpentity entity = response. getentity ();

Result = entityutils. tostring (entity, HTTP. utf_8 );

}

Return result;

}

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.