Transferred from: http://blog.sina.com.cn/s/blog_87216a0001014sm7.html
Using httpclient:
Namevaluepair NameValuePair1 =NewBasicnamevaluepair ("name", "Yang"); Namevaluepair NameValuePair2=NewBasicnamevaluepair ("pwd", "123123"); List Namevaluepairs=NewArrayList (); Namevaluepairs.add (NAMEVALUEPAIR1); Namevaluepairs.add (NAMEVALUEPAIR2); String Validateurl= "Http://10.0.2.2:8080/testhttp1/TestServlet";Try{httpparams Httpparams=NewBasichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparams,5000);//Setting the connection timeout to 5 secondsHttpClient Client=NewDefaulthttpclient (Httpparams);//generate an HTTP client send request objectHttpPost HttpPost=NewHttpPost (urlstring);//Set Request Mode if(namevaluepairs!=NULL&& namevaluepairs.size ()!=0) { //encodes a key-value pair and puts it into the Httpentity objectHttppost.setentity (Newurlencodedformentity (namevaluepairs,http. Utf_8)); } HttpResponse HttpResponse= Client.execute (HttpPost);//send a request and wait for a response//determine if the network connection is successful if(Httpresponse.getstatusline (). Getstatuscode ()! = 200) {System.out.println ("Network error exception!!!!"); return false; } httpentity Entity= Httpresponse.getentity ();//get the content inside the responseInputStream = Entity.getcontent ();//get the content of the response sent back by the service gas (all inside a stream)//get the content of the response sent back by the service gas (all inside a string)//String strresult = entityutils.tostring (entity); } Catch(Exception e) {System.out.println ("It's an anomaly!" "); }
Using httpurlconnection:
String validateurl= "http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123";Try{URL URL=NewURL (Validateurl);//Create a URL object//returns a URLConnection object that represents the connection to the remote object referenced by the URLHttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (5000);//Setting the connection timeout to 5 secondsConn.setrequestmethod ("GET");//Set Request ModeConn.connect ();//establish an actual connection to a remote object//returns the input stream for open connection readdatainputstream Dis=NewDataInputStream (Conn.getinputstream ()); //determine if the data is responding properly if(Conn.getresponsecode ()! =HTTPURLCONNECTION.HTTP_OK) {System.out.println ("Network error exception!!!!"); return false; }} Catch(Exception e) {e.printstacktrace (); System.out.println ("It's an anomaly!" "); } finally { if(Conn! =NULL) {conn.disconnect ();//Interrupt Connection } }
Two ways to access Android HTTP