07_android Introduction _ Use HttpClient Post mode, get method to implement the landing case respectively

Source: Internet
Author: User
Tags gettext

1. Brief introduction

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

2. Function Introduction

? ? The basic features provided by HttpClient are listed below, and there are many other specific features that can be found in the HttpClient home page.

(1) The implementation of all HTTP methods (Get,post,put,head, etc.) (2) support their own active steering (3) Support HTTPS Protocol (4) Support Agent Server 3. Processing steps

1. Create an instance of HttpClient
2. Create an instance of a connection method, for example: HttpGet.

Incoming address to be connected in HttpGet constructor
3. Call the Execute method of the created instance in the first step to run the second step to create a good instance of method
4. Read response
5. Release the connection. Regardless of whether the running method is successful. Must release the connection

6. Processing the content after it is received

4. Specific case description

1 . Continue to use 03_android to implement the landing interface with Relativelayout for this case layout file?

2.server end of the code with the 04_android introduction _ HttpURLConnection Get way to implement the landing case of the server code snippet (5. About server I write only one servlet to handle the corresponding request processing )

3. I wrote a tool class (Streamtools) code such as the following on the server side, which returns the processing of the stream object:

Package Www.csdn.net.util;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;public class Streamtools {/** * Convert stream object to string Object *  * @param is * @return */public static string stream Tostr (InputStream is) {try {//define byte array output stream object Bytearrayoutputstream os = new Bytearrayoutputstream ();//define read length int len = 0;// Defines the read buffer byte buffer[] = new byte[1024];//is looped through the defined buffer. Until the read is complete, the while (len = is.read (buffer))! =-1) {//writes to the byte array output stream object according to the length of the read os.write (buffer, 0, Len);} Close 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 is consistent with the service-side encoding without garbled problems. Android default encoding is UTF-8) return new String (data, "UTF-8");} catch (IOException e) {e.printstacktrace (); return null;}}}

4.LoginActivity code (in the code specifically added gaze, please read 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.httppost;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 ;p ublic class Loginactivity extends Activity {//DECLARE control private EditText et_name, et_pass;private TextView tv_result; @Overri deprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_login);//Gets the control pairLike 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)//server returns the control of the data display}/** * button click event Processing * @param v */public void login (View v) {//get control Idint id = v.getid (); switch (i d) {Case r.id.btn_login://gets the text content of the control final String userName = Et_name.gettext (). toString ();//Usernamefinal String Userpass = Et_pass.gettext (). toString ();//user password//infers if userName and password are empty if (Textutils.isempty (Username.trim ( ))|| Textutils.isempty (Userpass.trim ())) {Toast.maketext (this, "username or password cannot be empty", Toast.length_long). Show (); else {//Open thread processing new thread (new Runnable () {@Overridepublic void Run () {//Call: Loginbyhttpclientget (UserName, userpass);// Call: Loginbyhttpclientpost (UserName, Userpass); Loginbyhttpclientget (UserName, userpass);//Test}}). Start (); Break;default:break;}}  /** * Processing of post in HttpClient * @param userName * @param userpass */public void Loginbyhttpclientpost (String userName, String usErpass) {//1. Create an instance of HttpClient HttpClient client = new Defaulthttpclient ();//2. Create an instance of a connection method. Here is the HttpPost. The address to be connected is passed in the constructor of HttpPost string uri= "http://172.16.237.200:8080/video/login.do"; HttpPost HttpPost = new HttpPost (URI); try {//encapsulates the collection of pass parameters list<namevaluepair> parameters = new arraylist< Namevaluepair> ();//Add to this set the number of references you want to pass Parameters.Add (new Basicnamevaluepair ("username", username));p Arameters.add (New Basicnamevaluepair ("Userpass", Userpass));//Create a pass-through parameter encapsulates a solid object urlencodedformentity entity = new Urlencodedformentity ( Parameters, "UTF-8");//Set the encoding of the pass parameter//deposit the Entity object into the HttpPost object Httppost.setentity (entity);//3. Call the Execute method of the created instance in the first step to run the second step to create a good instance of method HttpResponse response = Client.execute (HttpPost); Httpurirequest descendant object//In the browser, tap enter//4. Read Responseif (Response.getstatusline (). Getstatuscode () ==200) {//Inferred status code InputStream is = Response.getentity (). GetContent ();//Get content final String result = Streamtools.streamtostr (IS); Convert text LoginActivity.this.runOnUiThread by tool class (new Runnable () {//through Runonuithread method processing @overridepublic void Run () {//sets the contents of the control (this content is obtained from the server side) Tv_result.settext (result);}});}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} FINALLY{//6. Release the connection. The connection Client.getconnectionmanager () must be released regardless of the success of the Run method. Shutdown ();}}  /** * Processed by Get mode in HttpClient * @param userName * @param userpass */public void Loginbyhttpclientget (String username,string Userpass) {//HttpClient send request get mode processing//1. Create an instance of HttpClient open a browser HttpClient client = new Defaulthttpclient ();//Defaulth Ttpclient extends Abstracthttpclienttry {//2. Create an instance of some kind of connection method. Here is the HttpGet. In httpget//'s constructor, pass in the address you want to connect to String URI = "Http://172.16.237.200:8080/video/login.do?"

Username= "+ username +" &userpass= "+ userpass;//emphasize that the address cannot appear localhost: operation httpget httpget = new HttpGet (URI);//3. Call the Execute method of the created instance in the first step to run the second step to create a good instance of method HttpResponse response = Client.execute (HttpGet); In the browser, hit the Enter//4. Read Responseint StatusCode = Response.getstatusline (). Getstatuscode ()//Read status code in status line if (StatusCode = = 200) {//assuming equals 2001 tangent OKH ttpentity entity = response.getentity ();//Returns a solid object InputStream is = Entity.getcontent (); Reads the contents of the entity final String result = Streamtools.streamtostr (IS); Convert text LoginActivity.this.runOnUiThread by tool class (new Runnable () {//@overridepublic void Run () {//by Runonuithread method) Sets the contents of the control (this content is obtained from the server side) Tv_result.settext (result);}});}} catch (Exception e) {e.printstacktrace ();} finally {//5. Release the connection. The connection Client.getconnectionmanager () must be released regardless of the success of the Run method. Shutdown ();//Release Link}}}


5. Operating effects such as

Hope to be of help to you!

07_android Introduction _ Use HttpClient Post mode, get method to implement the landing case respectively

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.