Java中發送POST請求并傳輸JSON結構體的方法如下:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpPostJsonUtil { public static String sendPostJson(String json, String url) throws Exception { // 創建連接 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 設置請求頭 con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); con.setRequestProperty("Accept", "application/json;charset=UTF-8"); // 設置POST請求 con.setRequestMethod("POST"); con.setDoOutput(true); // 發送POST請求傳輸JSON數據 con.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8)); // 獲取響應結果 String response = ""; BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response += inputLine; } in.close(); return response; } }
其中,通過URL對象創建連接,并設置請求頭為application/json;charset=UTF-8,Accept為application/json;charset=UTF-8,指定請求方法為POST,開啟doOutput并傳輸JSON數據。最后通過連接對象的getInputStream方法獲取響應結果,并通過BufferedReader讀取數據。