package org.example; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpRequestUtil { /** * 向指定URL发送POST请求,发送JSON数据 * @param urlStr 目标接口地址 * @param jsonData 发送的JSON字符串 * @return 响应内容 * @throws Exception 网络异常 */ public static String postJson(String urlStr, String jsonData) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); try (OutputStream os = conn.getOutputStream()) { os.write(jsonData.getBytes("UTF-8")); } int code = conn.getResponseCode(); if (code == 200) { try (java.io.InputStream is = conn.getInputStream()) { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } return new String(baos.toByteArray(), "UTF-8"); } } else { throw new RuntimeException("HTTP请求失败,状态码: " + code); } } /** * 向指定URL发送GET请求 * @param urlStr 目标接口地址 * @return 响应内容 * @throws Exception 网络异常 */ public static String get(String urlStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); int code = conn.getResponseCode(); if (code == 200) { try (java.io.InputStream is = conn.getInputStream()) { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } return new String(baos.toByteArray(), "UTF-8"); } } else { throw new RuntimeException("HTTP GET请求失败,状态码: " + code); } } }