一般作为工具类进行使用,POST请求需要带json格式的请求体,GET请求返回json格式的响应
package cn.omvn.utils; /** * 2023-10-05 * 栋dong */ import com.alibaba.fastjson.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpUtil { /** * GET 方式的http请求 * * @param httpUrl 请求地址 * @return 返回结果 */ public static String doGet(String httpUrl) { HttpURLConnection connection = null; InputStream inputStream = null; BufferedReader bufferedReader = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(httpUrl); // 通过远程url连接对象打开⼀个连接,强转成httpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置连接⽅式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); // 发送请求 connection.connect(); // 通过connection连接,获取输⼊流 if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); // 封装输⼊流,并指定字符集 bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = bufferedReader.readLine()) != null) { sbf.append(temp); sbf.append(System.getProperty("line.separator")); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != bufferedReader) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != inputStream) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect();// 关闭远程连接 } } return result; } /** * post 方式的http请求 * @param httpUrl 请求地址 * @param jsonInputString 请求参数 * @return 返回结果 */ public static JSONObject doPost(String httpUrl, String jsonInputString) { try { // 创建URL对象 URL url = new URL(httpUrl); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); // 启用输入和输出流 connection.setDoOutput(true); connection.setDoInput(true); // 设置请求头信息 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); // 写入JSON数据 try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } // 获取响应代码 int responseCode = connection.getResponseCode(); // 读取响应数据 if (responseCode == 200) { StringBuilder response = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(connection.getInputStream(), "utf-8"); BufferedReader in = new BufferedReader(reader)) { String line; while ((line = in.readLine()) != null) { response.append(line); } } return JSONObject.parseObject(response.toString()); } else { // 处理请求失败的情况 throw new RuntimeException("Request failed with response code: " + responseCode); } } catch (Exception e) { throw new RuntimeException("Error: " + e.getMessage()); } } }