One, using HttpURLConnection to send a GET request to the server
1. Send a GET request to the server
@Test publicvoid sendsms ()throwsexception{String Message= "The goods have been sent to"; Message=urlencoder.encode (Message, "UTF-8"); SYSTEM.OUT.PRINTLN (message); String Path= "Http://localhost:8083/DS_Trade/mobile/sim!add.do?message=" +message; URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (5*1000); Conn.setrequestmethod ("GET"); InputStream instream=Conn.getinputstream (); byte[] data =Streamtool.readinputstream (instream); String result=NewString (data, "UTF-8"); SYSTEM.OUT.PRINTLN (result); }
2. Read data from the server
String message=request.getparameter ("message");
Second, use HttpURLConnection to send a POST request to the server
1. Send a POST request to the server
@Test publicvoid addbyurl ()throwsexception{String Encoding= "UTF-8"; String params= "[{\" addtime\ ": \" 2011-09-19 14:23:02\ "[],\" iccid\ ": \" 1111\ ", \" id\ ": 0,\" imei\ ": \" 2222\ ", \" imsi\ ": \" 3333\ ", \" Phonetype\ ": \" 4444\ ", \" Remark\ ": \" aaaa\ ", \" tel\ ": \" 5555\ "}]"; String Path= "Http://localhost:8083/xxxx/xxx/sim!add.do"; byte[] data =params.getbytes (encoding); URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("POST"); Conn.setdooutput (true); //application/x-javascript text/xml->xml Data Application/x-javascript->json Object application/ x-www-form-urlencoded-> form DataConn.setrequestproperty ("Content-type", "APPLICATION/X-JAVASCRIPT; Charset= "+encoding); Conn.setrequestproperty ("Content-length", String.valueof (data.length)); Conn.setconnecttimeout (5*1000); OutputStream OutStream=Conn.getoutputstream (); Outstream.write (data); Outstream.flush (); Outstream.close (); System.out.println (Conn.getresponsecode ()); //Response Code 200 indicates success if(Conn.getresponsecode () ==200) {InputStream instream=Conn.getinputstream (); String result=NewString (Streamtool.readinputstream (instream), "UTF-8"); } }
2. Read data from the server
// get the data from the POST request byte [] data=Streamtool.readinputstream (Request.getinputstream ()); // [{\ "addtime\": \ "2011-09-19 14:23:02\" [],\ "iccid\": \ "1111\", \ "id\": 0,\ "imei\": \ "2222\", \ "imsi\": \ "3333\", \ " Phonetype\ ": \" 4444\ ", \" Remark\ ": \" aaaa\ ", \" tel\ ": \" 5555\ "}] string json=new string (data," UTF-8 ");
Use HttpURLConnection to send post and get requests to the server