07_android entry _ use the HttpClient POST method and GET method to implement login cases respectively

Source: Internet
Author: User

1. Introduction

HttpClient is a sub-project under Apache Jakarta Common. It can be used to provide an efficient, up-to-date, and function-rich client programming toolkit that supports HTTP protocol, it also supports the latest HTTP Version and recommendations.

2. Features

The main functions provided by HttpClient are listed below. For more details, see the HttpClient homepage.

(1) Implement all HTTP methods (GET, POST, PUT, HEAD, etc.) (2) Support automatic redirection (3) support HTTPS protocol (4) Support proxy server, etc. 3. procedure

1. Create an HttpClient instance
2. Create a connection method instance, such as HttpGet. Input the address to be connected in the HttpGet constructor.
3. Call the execute method of the Instance created in step 1 to execute the method Instance created in step 2.
4. Read response
5. Release the connection. The connection must be released no matter whether the execution method is successful or not.

6. process the obtained content

4. Detailed case description

1. Continue to use 03_android entry _ use RelativeLayout to implement the layout file of this case on the login interface

2. The server-side Code adopts the 04_android entry _ HttpURLConnection GET method to implement server code snippets in the login case (5. On the server, I only write a Servlet to process the corresponding requests)

3. I have written the following code to process the stream objects returned by the server:

Package www.csdn.net. util; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; public class StreamTools {/*** converts a stream object to a String object ** @ param is * @ return */public static String streamToStr (InputStream is) {try {// define ByteArrayOutputStream OS = new ByteArrayOutputStream (); // define the read length int len = 0; // define the read buffer byte buffer [] = new byte [1024]; // read cyclically according to the defined buffer until the read is complete While (len = is. read (buffer ))! =-1) {// write to the OS of the byte array output stream object based on the read length. write (buffer, 0, len);} // close the stream is. close (); OS. close (); // convert the read byte array output stream object to a byte array byte data [] = OS. toByteArray (); // convert to a string according to the specified encoding (this encoding must be consistent with the server-side encoding, so there will be no garbled problem, android default encoding is UTF-8) return new String (data, "UTF-8");} catch (IOException e) {e. printStackTrace (); return null ;}}}

4. LoginActivity Code (the code is annotated in detail. Please read it carefully)

Package www.csdn.net. lesson03; import java. io. inputStream; import java. util. arrayList; import java. util. list; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. httpClient; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpP Ost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import www.csdn.net. util. streamTools; import android. app. activity; import android. OS. bundle; import android. text. textUtils; import android. view. view; import android. widget. editText; import android. widget. textView; import android. widget. toast; public class LoginActivity extends Activity {// declare the control privat E EditText et_name, et_pass; private TextView TV _result; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_login); // obtain the control object et_name = (EditText) findViewById (R. id. et_name); // username control et_pass = (EditText) findViewById (R. id. et_pass); // password control TV _result = (TextView) findViewById (R. id. TV _result); // Control for displaying data returned by the server}/*** Click Event Processing * @ para M v */public void login (View v) {// obtain the control idint id = v. getId (); switch (id) {case R. id. btn_login: // get the control's text content final String userName = et_name.getText (). toString (); // username final String userPass = et_pass.getText (). toString (); // User Password // determine whether the user name and password are empty if (TextUtils. isEmpty (userName. trim () | TextUtils. isEmpty (userPass. trim () {Toast. makeText (this, "the user name or password cannot be blank", Toast. LENGTH_LONG ). show ();} else {// enable thread processing new T Hread (new Runnable () {@ Overridepublic void run () {// call: callback (userName, userPass); // call: loginByHttpClientPost (userName, userPass); loginByHttpClientGet (userName, userPass); // test }}). start ();} break; default: break;}/*** POST processing in HttpClient * @ param userName * @ param userPass */public void loginByHttpClientPost (String userName, string userPass) {// 1. httpClient client = ne W DefaultHttpClient (); // 2. Create an instance of a connection method. Here it is HttpPost. Input the URL String uri = "http: // 172.16.237.200: 8080/video/login in the http POST constructor. do "; HttpPost httpPost = new HttpPost (uri); try {// encapsulate the List of passed parameters
 
  
Parameters = new ArrayList
  
   
(); // Add the parameter parameters to the set. add (new BasicNameValuePair ("username", userName); parameters. add (new BasicNameValuePair ("userpass", userPass); // create a Pass Parameter encapsulate the object UrlEncodedFormEntity entity = new UrlEncodedFormEntity (parameters, "UTF-8 "); // set the encoding of the passed parameters // Save the object to httpPost. setEntity (entity); // 3. call the execute method of the Instance created in step 1 to execute the method Instance HttpResponse response = client.exe cute (httpPost) created in step 2; // HttpUri The descendant object of the Request // press enter in the browser // 4. read responseif (response. getStatusLine (). getStatusCode () = 200) {// status code InputStream is = response. getEntity (). getContent (); // get the final String result = StreamTools. streamToStr (is); // use the tool class to convert the text LoginActivity. this. runOnUiThread (new Runnable () {// use the runOnUiThread method to process @ Overridepublic void run () {// set the control content (this content is obtained from the server) TV _result.setText (result) ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {// 6. Release the connection. The Connection client must be released no matter whether the execution method is successful or not. getConnectionManager (). shutdown () ;}/ *** @ param userName * @ param userPass */public void loginByHttpClientGet (String userName, String userPass) processed in the GET method in httpClient) {// HttpClient send request GET Method Processing // 1. create an HttpClient instance open a browser HttpClient client = new DefaultHttpClient (); // DefaultHttpClient extends acthttpclienttry {// 2. create an instance of a connection method. Here it is HttpGet. Input the URL String uri = "http: // 172.16.237.200: 8080/video/login. do? In the HttpGet // constructor? Username = "+ userName +" & userpass = "+ userPass; // indicates that the address cannot contain localhost: operate HttpGet httpGet = new HttpGet (uri); // 3. call the execute method of the Instance created in step 1 to execute the method Instance HttpResponse response = client.exe cute (httpGet) created in step 2 ); // press enter in the browser. // 4. read responseint statusCode = response. getStatusLine (). getStatusCode (); // read the status code in the status line if (statusCode = 200) {// if it is equal to 200 All okHttpEntity entity = response. getEntity (); // returns the Inpu object. TStream is = entity. getContent (); // read the final String result = StreamTools in the object. streamToStr (is); // use the tool class to convert the text LoginActivity. this. runOnUiThread (new Runnable () {// use the runOnUiThread method to process @ Overridepublic void run () {// set the control content (this content is obtained from the server) TV _result.setText (result) ;}} catch (Exception e) {e. printStackTrace ();} finally {// 5. release the connection. Whether the execution method is successful or not, you must release the Connection client. getConnectionManager (). shutdown (); // release the link }}}
  
 

5. The running effect is as follows:

Hope to help you!

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.