java原生http請求的實現是依賴 java.net.URLConnection
post請求的demo
public class Main { public static void main(String[] args) { postDemo(); } /** * POST請求 */ public static void postDemo() { try { // 請求的地址 String spec = "http://localhost:9090/formTest"; // 根據地址創建URL對象 URL url = new URL(spec); // 根據URL對象打開鏈接 HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); // 設置請求方法 urlConnection.setRequestMethod("POST"); // 設置請求的超時時間 urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); // 傳遞的數據 String data = "name=" + URLEncoder.encode("aaa", "UTF-8") + "&school=" + URLEncoder.encode("bbbb", "UTF-8"); // 設置請求的頭 urlConnection.setRequestProperty("Connection", "keep-alive"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length)); // 發送POST請求必須設置允許輸出 urlConnection.setDoOutput(true); // 發送POST請求必須設置允許輸入 urlConnection.setDoInput(true); //setDoInput的默認值就是true //獲取輸出流,將參數寫入 OutputStream os = urlConnection.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); urlConnection.connect(); if (urlConnection.getResponseCode() == 200) { // 獲取響應的輸入流對象 InputStream is = urlConnection.getInputStream(); // 創建字節輸出流對象 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 定義讀取的長度 int len = 0; // 定義緩沖區 byte[] buffer = new byte[1024]; // 按照緩沖區的大小,循環讀取 while ((len = is.read(buffer)) != -1) { // 根據讀取的長度寫入到os對象中 byteArrayOutputStream.write(buffer, 0, len); } // 釋放資源 is.close(); byteArrayOutputStream.close(); // 返回字符串 String result = new String(byteArrayOutputStream.toByteArray()); System.out.println(result); } else { System.out.println("請求失敗"); } } catch (Exception e) { e.printStackTrace(); } } }