Java Network Programming Note 3
Refer to the following code for how to use POST and GET requests to send requests to the Web site:
Import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java.net. URL; import java.net. URLConnection; public class GetTest {private String url; private String param;/***** @ param url sends the request URL * @ param request parameter, the format is in the format of name1 = value1 & name2 = value2 */public GetTest (String url, String param) {this. url = url; this. param = param;} public String sendGet () throws Exception {Stri Ng result =; String urlName = url +? + Param; URL surl = new URL (urlName); // enable the URL Connection URLConnection conn = surl. openConnection (); // set the common request attribute conn. setRequestProperty (accept, */*); conn. setRequestProperty (connection, Keep-Alive); // create the actual connection conn. connect (); // defines the byte stream InputStream is = conn. getInputStream (); // wrap response stream InputStreamReader isr = new InputStreamReader (is, UTF-8); // Add buffer BufferedReader br = new BufferedReader (isr); String line; while (null! = (Line = br. readLine () {result + = line;} br. close (); isr. close (); is. close (); return result ;}}
Import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java. io. printWriter; import java.net. URL; import java.net. URLConnection; public class PostTest {private String url; private String param;/***** @ param url sends the request URL * @ param request parameter, the format is in the format of name1 = value1 & name2 = value2 */public PostTest (String url, String param) {this. url = url; this. param = param;} public String se NdGet () throws Exception {String result =; URL surl = new URL (url); // enable the URL Connection URLConnection conn = surl. openConnection (); // set the common request attribute conn. setRequestProperty (accept, */*); conn. setRequestProperty (connection, Keep-Alive); // The following two rows of conn must be set to send a POST request. setDoOutput (true); conn. setDoInput (true); PrintWriter pw = new PrintWriter (conn. getOutputStream (); // sends the request pw. print (param); pw. flush (); // defines the byte stream InputStream is = conn. getInputSt Ream (); // wrap the response stream InputStreamReader isr = new InputStreamReader (is, UTF-8); // Add the buffer BufferedReader br = new BufferedReader (isr); String line; while (null! = (Line = br. readLine () {result + = line;} br. close (); isr. close (); is. close (); return result ;}}