Android communication HttpClient

Source: Internet
Author: User

Android communication HttpClient

The following is a small example of using HttpClient to log on to the server.

Package com. liang. logindemo; import android. OS. bundle; import android. support. v7.app. actionBarActivity; import android. view. view; import android. widget. editText; import android. widget. toast; 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. httpGe T; import org. apache. http. client. methods. httpPost; import org. apache. http. entity. bufferedHttpEntity; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. reader; import java. io. stringReader; import java. io. unsupportedEncod IngException; import java.net. httpURLConnection; import java.net. URL; import java.net. URLEncoder; import java. util. arrayList; import java. util. list; public class MainActivity3 extends ActionBarActivity {private EditText et_userName; private EditText et_password; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); et _ UserName = (EditText) findViewById (R. id. et_userName); et_password = (EditText) findViewById (R. id. et_password);} public void login (View view) {String str = et_userName.getText (). toString (); try {str = URLEncoder. encode (str, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} final String userName = str; final String password = et_password.getText (). toString (); // access the network new Thread in the Child Thread (New Runnable () {@ Override public void run () {try {final boolean isSuccess = loginByPost (userName, password); // final boolean isSuccess = loginByGet (userName, password ); // you do not need to use Handler to notify the main thread to use this method. The main thread completes runOnUiThread (new Runnable () {@ Override public void run () {if (isSuccess) {Toast. makeText (MainActivity3.this, "succeeded !!! ", Toast. LENGTH_SHORT). show ();} else {Toast. makeText (MainActivity3.this," failed !!! ", Toast. LENGTH_SHORT ). show () ;}}) ;}catch (Exception e) {e. printStackTrace ();}}}). start ();}/*** HttpClient accesses the server through a GET request * @ param userName, password * @ return * @ throws Exception */private Boolean loginByGet (String userName, string password) throws Exception {// server address String url = "http: // 192.168.1.140: 8080/Login/servlet/Login"; String data = "? UserName = "+ userName +" & password = "+ password; HttpClient client = null; // define a client = new DefaultHttpClient (); // define a get request HttpGet = new HttpGet (url + data); // execute the get request to obtain the response object HttpResponse response = client.exe cute (get ); // get the response status code int code = response. getStatusLine (). getStatusCode (); // return result if (code = 200) {// get response content InputStream is = response. getEntity (). getContent (); BufferedReader reader = new Bu FferedReader (new InputStreamReader (is); String text = reader. readLine (); reader. close (); is. close (); return "SUCCESS". equals (text )? True: false;} if (client! = Null) {// close the connection to the client. getConnectionManager (). shutdown ();} return false ;} /*** HttpClient accesses the server through POST Request * @ param userName * @ param password * @ return * @ throws Exception */boolean loginByPost (String userName, String password) throws Exception {// server address String url = "http: // 192.168.1.140: 8080/Login/servlet/Login"; HttpClient client = null; // define a client = new DefaultHttpClient (); // define a Post request HttpPost post = new HttpPost (url); // set the request data List
 
  
List = new ArrayList
  
   
(); List. add (new BasicNameValuePair ("userName", userName); list. add (new BasicNameValuePair ("password", password); UrlEncodedFormEntity entity = new UrlEncodedFormEntity (list); post. setEntity (entity); // execute the get request to obtain the response object HttpResponse response = client.exe cute (post); // obtain the response status code int code = response. getStatusLine (). getStatusCode (); // return result if (code = 200) {// get response content InputStream is = response. getEntity (). getCo Ntent (); BufferedReader reader = new BufferedReader (new InputStreamReader (is); String text = reader. readLine (); reader. close (); is. close (); return "SUCCESS ". equals (text )? True: false;} if (client! = Null) {// close the Connection client. getConnectionManager (). shutdown () ;}return false ;}}
  
 

You need to add network access permissions to the configuration file.


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.