在Java中,有兩種常見的HTTP請求方法:POST和GET。
GET方法:
GET方法是通過URL傳遞數據的一種請求方式。當使用GET方法請求網頁時,瀏覽器會把所有的數據放在URL的后面,并使用問號(?)作為分隔符。使用GET方式傳遞數據的URL長度有限制,大約是2048個字符。因此,一般使用GET方法進行小數據量的請求。
URL url; HttpURLConnection con; BufferedReader in; String result = ""; String line; try { url = new URL("http://www.baidu.com/s?wd=java"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); in = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = in.readLine()) != null) { result += line; } in.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println(result);
POST方法:
POST方法是通過HTTP請求體發送數據的方法。POST請求不會像GET請求一樣在URL后面帶上數據,而是把請求的數據放在請求體中進行傳遞。使用POST方法傳遞的數據量一般不受限制。
URL url; HttpURLConnection con; OutputStreamWriter out; BufferedReader in; String result = ""; String line; try { url = new URL("http://localhost:8080/myWeb/login"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); out = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); String params = "username=admin&password=123456"; out.write(params); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = in.readLine()) != null) { result += line; } in.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println(result);