HttpURLConnection have get and post requests, respectively
Post-mode
1 Public voidTestpostbendi ()throwsException {2 //Build Server Address3URL url =NewURL ("http://192.168.40.194/qiantai/admin/login_check.php");4 //Get HttpURLConnection Object5HttpURLConnection httpurlconnection =(HttpURLConnection) url.openconnection ();6 //Set Request Time7Httpurlconnection.setreadtimeout (10000);8Httpurlconnection.setconnecttimeout (10000);9 //Setup ModeTenHttpurlconnection.setrequestmethod ("POST"); One //Create an actual link A Httpurlconnection.connect (); - //Get output stream -OutputStream OS =Httpurlconnection.getoutputstream (); the //Post-submitted fields -String message = "username=admin&userpass=123456"; - //want the server to write data - Os.write (Message.getbytes ()); + //Gets the status code returned by the server - intCode =Httpurlconnection.getresponsecode (); + //Switch to Judge A Switch(code) { at Case201: - Case200: - //gets the input stream returned by the server -InputStream InputStream =Httpurlconnection.getinputstream (); -StringBuffer StringBuffer =NewStringBuffer (); - String strings; in //convert into character input stream -BufferedReader BufferedReader =NewBufferedReader (NewInputStreamReader (InputStream)); to while((strings = Bufferedreader.readline ())! =NULL){ + Stringbuffer.append (strings); - } the //Close Data Link * Httpurlconnection.disconnect (); $LOG.E (TAG, "Testurl:" +stringbuffer.tostring ());Panax Notoginseng Break; - Case60s: theLOG.E (TAG, "tes401 =========================================================="); + Break; A } the}
Get mode of
Public voidTesturl ()throwsException {//Build URLsURL url =NewURL ("http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=15850781443"); //Get HttpURLConnectionHttpURLConnection httpurlconnection =(HttpURLConnection) url.openconnection (); //set up supermarket timeHttpurlconnection.setconnecttimeout (10000); Httpurlconnection.setreadtimeout (10000); //Set Request ModeHttpurlconnection.setrequestmethod ("GET"); //GET Request Code intCode =Httpurlconnection.getresponsecode (); Switch(code) { Case200: InputStream inputstream=Httpurlconnection.getinputstream (); StringBuffer SB=NewStringBuffer (); String str; BufferedReader Reader=NewBufferedReader (NewInputStreamReader (InputStream)); while(str = reader.readline ())! =NULL) {sb.append (str+ "\ n"); } log.e (TAG,"Testurl:" +sb.tostring ()); Break; Case401: LOG.E (TAG,"Testurl:401"); Break; } }
Android Learning Note--http protocol