Java語言中的get和post都是HTTP協議中常用的兩種請求方式。它們同樣可以傳送數據,但是傳送的方式卻有所不同。
HTTP協議中的get請求方式是將所需查詢的信息拼成URL后跟在后面,通過瀏覽器發送請求獲取數據。get請求的數據會顯示在URL中,可以直接查看,但是數據量有限制,對于一些需要傳送大量數據的請求就不能滿足要求。下面是Java語言中實現get請求的代碼:
URL url = new URL("http://example.com/api/getData"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString());
而post請求方式則是將所需傳輸的數據放在HTTP請求體中,提交到服務器上處理,post請求的數據不會顯示在URL中,可以傳輸大量的數據。下面是Java語言中實現post請求的代碼:
URL url = new URL("http://example.com/api/postData"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); String postData = "name=example&age=25"; //需要傳輸的數據 out.write(postData); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString());
綜上所述,get和post請求在HTTP協議中都有各自的特點,在Java語言中實現也各有不同。需要根據具體的傳輸需求選擇相應的請求方式。