Java中的Post請求帶Json參數是通過HttpURLConnection來實現的。以下是實現步驟:
try { URL url = new URL("http://example.com/your_endpoint"); HttpURLConnection con = (HttpURLConnection ) url.openConnection(); // 設置請求方法為POST con.setRequestMethod("POST"); // 設置請求頭 con.setRequestProperty("Content-Type", "application/json;charset=utf-8"); con.setRequestProperty("Accept", "application/json"); // 開啟輸出流 con.setDoOutput(true); // 構造請求Json數據 JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "Jack"); jsonObject.put("age", "25"); String requestBody = jsonObject.toString(); // 發送請求并寫入數據 OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(requestBody); out.flush(); out.close(); // 獲取響應狀態碼 int responseCode = con.getResponseCode(); if(responseCode == 200) { // 獲取響應內容 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String responseLine; StringBuffer response = new StringBuffer(); while ((responseLine = in.readLine()) != null) { response.append(responseLine); } in.close(); // 處理響應內容 JSONObject responseJson = new JSONObject(response.toString()); System.out.println(responseJson); } else { System.out.println("請求失敗:"+responseCode); } } catch (IOException e) { e.printStackTrace(); }
以上代碼實現了一個簡單的Post請求帶Json參數的示例,可以根據需要進行修改和擴展。