ImportJava.io.*;ImportJava.net.URL;ImportJava.util.Map;Importjava.net.HttpURLConnection;; Public classhttprequest{ Public Staticstring sendget (string url) {string result= ""; BufferedReader in=NULL; Try{URL Realurl=Newurl (URL); HttpURLConnection Connection=(HttpURLConnection) realurl.openconnection (); Connection.setconnecttimeout (5000); Connection.setrequestmethod ("GET"); Inch=NewBufferedReader (NewInputStreamReader (Connection.getinputstream ())); String Line; while(line = In.readline ())! =NULL) {result+=Line ; } } Catch(Exception e) {System.out.println ("Send GET Request failed:" +e); E.printstacktrace (); } finally { Try { if(In! =NULL) {in.close (); } } Catch(Exception E2) {e2.printstacktrace (); } } returnresult; } Public Staticstring sendpost (string url, string params) {string encoding= "UTF-8"; String result= ""; BufferedReader in=NULL; Try { byte[] data =params.getbytes (encoding); URL Base_url=Newurl (URL); HttpURLConnection Conn=(HttpURLConnection) base_url.openconnection (); Conn.setreadtimeout (5000); Conn.setrequestmethod ("POST"); Conn.setdooutput (true); Conn.setdoinput (true); Conn.setrequestproperty ("Content-type", "Application/json"); Conn.setrequestproperty ("Content-length", String.valueof (data.length)); OutputStream OutStream=Conn.getoutputstream (); Outstream.write (data); Outstream.flush (); Outstream.close (); System.out.println (Conn.getresponsecode ()); System.out.println (Conn.getresponsemessage ()); if(Conn.getresponsecode () = = 200) { in=NewBufferedReader (NewInputStreamReader (Conn.getinputstream ())); String Line; while(line = In.readline ())! =NULL) {result+=Line ; } } } Catch(Exception e) {System.out.println ("Send POST request failed:" +e); E.printstacktrace (); } finally { Try { if(In! =NULL) {in.close (); } } Catch(Exception E2) {e2.printstacktrace (); } } returnresult; }}
Java send get and post requests for HTTP