Network Programming is indispensable for anyone who has been familiar with Android Application Development. as a client, Android applications do not have much to do without services on the server. Therefore, they must interact with the server, network Programming is required. As far as I am concerned, there are three network programming methods for Android.
Method 1: Use httpurlconnection as follows:
Using the httpurlconnection object, we can send request parameters to the network.
String requesturl = http :/// localhost: 8080/itcast/contanctmanage. do; Map <string, string> requestparams = new hashmap <string, string> (); requestparams. put ("Age", "12"); requestparams. put ("name", "China"); stringbuilder Params = new stringbuilder (); For (map. entry <string, string> entry: requestparams. entryset () {Params. append (entry. getkey (); Params. append ("="); Params. append (urlencoder. encode (entry. getvalue (), "UTF-8"); Params. append ("&");} If (Params. length ()> 0) Params. deletecharat (Params. length ()-1); byte [] DATA = Params. tostring (). getbytes (); Url realurl = new URL (requesturl); httpurlconnection conn = (httpurlconnection) realurl. openconnection (); Conn. setdooutput (true); // to send a POST request, you must set to allow the output of Conn. setusecaches (false); // do not use cacheconn. setrequestmethod ("Post"); Conn. setrequestproperty ("connection", "keep-alive"); // maintain the persistent connection Conn. setrequestproperty ("charset", "UTF-8"); Conn. setrequestproperty ("Content-Length", String. valueof (data. length); Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded"); dataoutputstream outstream = new dataoutputstream (Conn. getoutputstream (); outstream. write (data); outstream. flush
Method 2: Use httpclient as follows:
Httpclient client = new defaulthttpclient (); // create an httpclient httppost request = new httppost (); // create an HTTP request using an instance. seturi (New uri ("http://code.google.com/android/"); // set the HTTP parameter list <namevaluepair> postparameters = new arraylist <namevaluepair> (); postparameters. add (New basicnamevaluepair ("one", "valuegoeshere"); urlencodedformentity formentity = new urlencodedformentity (postparameters); Request. setentity (formentity); httpresponse response = client.exe cute (request); // call bufferedreader in = new bufferedreader (New inputsteamreader (response. getentity. getcontent); // process the HTTP Response
Method 3: Use androidhttpclient
In actual projects, when method 1 is used, it takes a long time to connect to the server,
Method 2: When connecting to the server, the speed is relatively fast. When the network is good, it will be connected in 3 seconds,
Strongly recommended method 2: httpclient.