Apache package is a good package for Android networking access and is the most commonly used class for Android access to the network.
Here's how to implement a Get,post request with HttpClient, respectively.
1.Get Request
HttpGet get = new HttpGet ("http://www.baidu.com"); HttpClient hclient = new Defaulthttpclient (); HttpResponse = Hclient.execute (get);
2.Post Request
map<string, string> map = new hashmap<string, string> (), Map.put ("id", id), Map.put ("name", name), Map.put (" Permission ", string.valueof (permission)); list<namevaluepair> list = new arraylist<namevaluepair> (); if (map! = null &&!map.isempty ()) {for (map.entry<string, string> entry:map.entrySet ()) {///iterators//Key-value pairs Nameva Luepair Namevaluepair = new Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()); List.add (Namevaluepair); }}urlencodedformentity entity = new Urlencodedformentity (list, encode);//use Post to submit data httppost post = new HttpPost (path) ;p ost.setentity (entity);//request body in//default client httpClient = HttpClient; HttpResponse HttpResponse = Client.execute (POST);
3. code example:
First GET request
Import Java.io.BufferedReader; Import java.io.IOException; Import Java.io.InputStream; Import Java.io.InputStreamReader; Import org.apache.http.HttpEntity; Import Org.apache.http.HttpResponse; Import org.apache.http.client.ClientProtocolException; Import org.apache.http.client.HttpClient; Import Org.apache.http.client.methods.HttpGet; Import org.apache.http.impl.DefaultHttpClientConnection; Import org.apache.http.impl.client.DefaultHttpClient; Import android.app.Activity; Import Android.os.Bundle; Import Android.view.Menu; Import Android.view.MenuItem; Import Android.view.View; Import Android.view.View.OnClickListener; Import Android.widget.Button; public class Mainactivity extends Activity {private Button Requestbutton; Private HttpResponse HttpResponse; Private httpentity entity; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Requestbutton = (Button) Findviewbyid (R.id.requestbutton); Requestbutton.setonclicklistener (New Onclicklistener () {public void OnClick (View v) { New Thread (New Downtest ()). Start (); } }); } class Downtest implements runnable{public void run () {//Generate a Request object, request HttpGet get = N EW HttpGet ("http://www.baidu.com"); Generates an HTTP client object HttpClient hclient = new Defaulthttpclient (); Use HTTP client to send Request object InputStream InputStream = null; try {HttpResponse = Hclient.execute (get),//httpresponse return response//Return response data is placed inside entity = httpresponse.getentity (); InputStream = Entity.getcontent (); BufferedReader reader = new BufferedReader (new InputStreamReader (InputStream)); String result = ""; String line = ""; while (line = Reader.readline ())! = null) {result = result+ line; } System.out.println (Result); } catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktra CE (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }finally{try{inputstream.close (); }catch (Exception e) {e.printstacktrace (); } } } } }
Again a POST request
public class Accounthttputils {//private static String PATH = "Http://192.168.253.1:8088/CallName/servlet/AccountS Ervler "; private static HttpClient HttpClient; Public accounthttputils (HttpClient HttpClient) {this.httpclient = HttpClient; } public static string Sendhttpclient (String path,map<string,string> map,string encode) {List<namevalu epair> list = new arraylist<namevaluepair> (); if (map! = null &&!map.isempty ()) {for (map.entry<string, string> entry:map.entrySet ()) {//iterator Key-value pairs namevaluepair Namevaluepair = new Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()); List.add (Namevaluepair); }} try {//implement encapsulates the requested parameter into the form, urlencodedformentity entity = new Urlencodedformentity (list , encode); Submit data using post HttpPost post = new HttpPost (path); Post.setentity (entity);//In the request body Default clients HttpClient client = HttpClient; HttpResponse HttpResponse = Client.execute (POST); if (Httpresponse.getstatusline (). Getstatuscode () = = () {httpentity httpentity = httpresponse.getentity (); InputStream InputStream = Httpentity.getcontent (); Return Changeinputestream (InputStream, encode); }} catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace () ; } catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktrace (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } return ""; /** * Convert an input stream into a string * @param inputstream * @param encode * @return * * * private static string C Hangeinputestream (InputStream inputstream,string encode) {//often called memory stream, written in memory BytearrayoutputstrEAM outputstream = new Bytearrayoutputstream (); byte[] data = new byte[1024]; int len = 0; String result = ""; if (InputStream! = null) {try {while (len = inputstream.read (data))!=-1) { Data.tostring (); Outputstream.write (data, 0, Len); }//result is the result = new String (Outputstream.tobytearray (), encode) in the Dopost function set on the server side; Outputstream.flush (); Outputstream.close (); Inputstream.close (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }} return result; } public static string set (String id,string name,int permission) {//TODO auto-generated method stub map<string, string> map = new hashmap<string, string> (); Map.put ("id", ID); Map.put ("name", name); Map.put ("Permission", string.valueof (permission)); String result = Accounthttputils.sendhttpclient (abstracthttputils.path+ "Servlet/accountservler", Map, "Utf-8"); SYSTEM.OUT.PRINTLN ("Result:" + result); return result; } }
4.get request to access is Baidu, the return is Baidu home source code
Post is a class in one of my small projects
But the structure is already very clear ....
Keep the spare ...
Http://www.cnblogs.com/jycboy/p/httpclient.html
Android's HttpClient