GET request
/*** Get JSON data from the network (String byte[})
* @paramPath *@return */ Public Staticstring Getjsonbyinternet (string path) {Try{URL URL=NewURL (Path.trim ()); //Open ConnectionHttpURLConnection URLConnection =(HttpURLConnection) url.openconnection (); if(200 = =Urlconnection.getresponsecode ()) { //Get input streamInputStream is =Urlconnection.getinputstream (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); byte[] buffer =New byte[1024]; intLen = 0; while( -1! = (len =is.read (buffer))) {baos.write (buffer,0, Len); Baos.flush (); } returnBaos.tostring ("Utf-8"); } } Catch(IOException e) {e.printstacktrace (); } return NULL; }
POST request
//get data from other pages /*** POST request data acquisition*/ Public Staticstring Postdownloadjson (String path,string post) {URL URL=NULL; Try{URL=NewURL (path); HttpURLConnection HttpURLConnection=(HttpURLConnection) url.openconnection (); Httpurlconnection.setrequestmethod ("POST");//Commit Mode//Conn.setconnecttimeout (10000);//Connection Timeout Unit milliseconds//conn.setreadtimeout (+);//read Timeout unit milliseconds//to send a POST request, you must set the following two linesHttpurlconnection.setdooutput (true); Httpurlconnection.setdoinput (true); //gets the output stream corresponding to the URLConnection objectPrintWriter PrintWriter =NewPrintWriter (Httpurlconnection.getoutputstream ()); //Send Request ParametersPrintwriter.write (POST);//the parameters of post Xx=xx&yy=yy//buffer for flush output streamPrintwriter.flush (); //start getting DataBufferedinputstream bis =NewBufferedinputstream (Httpurlconnection.getinputstream ()); Bytearrayoutputstream Bos=NewBytearrayoutputstream (); intLen; byte[] arr =New byte[1024]; while((Len=bis.read (arr))! =-1) {bos.write (arr),0, Len); Bos.flush (); } bos.close (); returnBos.tostring ("Utf-8"); } Catch(Exception e) {e.printstacktrace (); } return NULL; }
httpurlconnection--get requests and post requests in two ways for network requests