Connect to the network via HttpClient mode

Source: Internet
Author: User

Xml:

1<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"2Xmlns:tools= "Http://schemas.android.com/tools"3Android:layout_width= "Match_parent"4android:layout_height= "Match_parent"5android:paddingbottom= "@dimen/activity_vertical_margin"6android:paddingleft= "@dimen/activity_horizontal_margin"7android:paddingright= "@dimen/activity_horizontal_margin"8android:paddingtop= "@dimen/activity_vertical_margin"9tools:context= "Com.zzw.request.MainActivity" >Ten  One<EditText AAndroid:id= "@+id/username" -Android:layout_width= "Match_parent" -android:layout_height= "Wrap_content" theAndroid:hint= "Please enter user name"/> -  -<EditText -Android:id= "@+id/password" +Android:layout_width= "Match_parent" -android:layout_height= "Wrap_content" +android:layout_below= "@id/username" Aandroid:hint= "Enter password"/> at  -<Button -Android:id= "@+id/get" -Android:layout_width= "Match_parent" -android:layout_height= "Wrap_content" -android:layout_below= "@id/password" inandroid:onclick= "Getclient" -android:text= "Get Request"/> to  +<Button -Android:id= "@+id/post" theAndroid:layout_width= "Match_parent" *android:layout_height= "Wrap_content" $android:layout_below= "@id/get"Panax Notoginsengandroid:onclick= "Postclient" -Android:text= "POST request"/> the  +</RelativeLayout>

Java code:

1 Packagecom.zzw.httpClient; 2 3ImportJava.io.ByteArrayOutputStream; 4Importjava.io.IOException; 5ImportJava.io.InputStream; 6Importjava.util.ArrayList; 7Importjava.util.List; 8 9Importorg.apache.http.HttpEntity;10ImportOrg.apache.http.HttpResponse;11ImportOrg.apache.http.NameValuePair;12Importorg.apache.http.client.ClientProtocolException;13Importorg.apache.http.client.HttpClient;14Importorg.apache.http.client.entity.UrlEncodedFormEntity;15ImportOrg.apache.http.client.methods.HttpGet;16ImportOrg.apache.http.client.methods.HttpPost;17Importorg.apache.http.impl.client.DefaultHttpClient;18Importorg.apache.http.impl.conn.DefaultClientConnection;19ImportOrg.apache.http.message.BasicNameValuePair;20 21Importandroid.app.Activity;22ImportAndroid.os.Bundle;23ImportAndroid.view.Menu;24ImportAndroid.view.MenuItem;25ImportAndroid.view.View;26ImportAndroid.widget.EditText;27ImportAndroid.widget.Toast;28 29 Public classMainactivityextendsActivity {EditText Username_et =NULL; EditText Password_et =NULL; 32 33@Override34protected voidonCreate (Bundle savedinstancestate) {35Super. OnCreate (savedinstancestate);36Setcontentview (r.layout.activity_main);PNS Username_et =(EditText) Findviewbyid (r.id.username);Password_et =(EditText) Findviewbyid (R.id.password);39     } 40 41 Public voidgetclient (view view) {42NewThread (NewRunnable () {43@Override44 Public voidrun () {45Try { 46//1. Get a client, equivalent to a browserHttpClient client =Newdefaulthttpclient ();48//2. Define a GET request, and encapsulate the parametersThe String data = "Username=" + username_et.gettext (). toString () + "&password=" 50 +Password_et.gettext (). toString ();Wuyi HttpGet get =NewHttpGet ("Http://10.0.2.2:8080/baidu/LoginServelt?" +data); 52//3. Use a well-defined browser to request an addressHttpResponse response =Client.execute (get);54intStatus =response.getstatusline (). Getstatuscode ();55if(Status = = 200) { 56FinalString content =Getstringfromstream (Response.getentity (). getcontent ());Runonuithread (NewRunnable () {58@Override59 Public voidrun () {Toast.maketext (mainactivity. This, "Return info:" + content, 0). Show (); 61                             } 62                         }); 63 64                     } 65}Catch(clientprotocolexception e) {66//TODO auto-generated Catch block67e.printstacktrace ();68}Catch(IOException e) {69//TODO auto-generated Catch block70e.printstacktrace ();71                 } 72 73             } 74}). Start (); 75     } 76 77 Public voidpostclient (view view) {78NewThread (NewRunnable () {79@Override80 Public voidrun () {81Try { 82//1. Get ClientHttpClient client =Newdefaulthttpclient ();84//2. Get post request and set parametersHttpPost post =NewHttpPost ("Http://10.0.2.2:8080/baidu/LoginServelt"); list<namevaluepair> parameters =NewArraylist<namevaluepair>(); Namevaluepair Nameuser =NewBasicnamevaluepair ("username", Username_et.gettext (). toString ()); Namevaluepair PassWord =NewBasicnamevaluepair ("PassWord", Password_et.gettext (). toString ()); 89Parameters.Add (nameuser);90Parameters.Add (PassWord);httpentity entity =NewUrlencodedformentity (Parameters, "UTF-8"); 93post.setentity (entity);94//3. Perform POST requestHttpResponse response =Client.execute (POST);96intStatus =response.getstatusline (). Getstatuscode ();97if(Status = = 200) { 98FinalString content =Getstringfromstream (Response.getentity (). getcontent ());Runonuithread (NewRunnable () {100 101@Override102 Public voidrun () {103 Toast.maketext (mainactivity. This, "POST:" +content,0). Show ();104                             }105                         });106 107 108                     }109}Catch(clientprotocolexception e) {110//TODO auto-generated Catch block111e.printstacktrace ();112}Catch(IOException e) {113//TODO auto-generated Catch block114e.printstacktrace ();115                 }116             }117}). Start ();118     }119 120 PublicString Getstringfromstream (InputStream in)throwsIOException {121byte[] buffer =New byte[1024];122 Bytearrayoutputstream ByteArray =NewBytearrayoutputstream ();123intLeng = 0;124 while((Leng = in.read (buffer, 0, 1024))! =-1) {125bytearray.write (buffer);126         }127 String content =bytearray.tostring ();128bytearray.close ();129returncontent;130     }131}

Connect to the network via HttpClient mode

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.