wanglizhong
2025-05-04 2841e102ea4b5e9ddd40327829431a25a9122cd9
ruoyi-common/src/main/java/com/ruoyi/common/utils/HttpUtil.java
@@ -116,4 +116,74 @@
        
        return response.toString();
    }
    /**
     * 发送GET请求
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String get(String url, Map<String, String> params) {
        StringBuilder response = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            // 构建带参数的URL
            StringBuilder urlBuilder = new StringBuilder(url);
            if (params != null && !params.isEmpty()) {
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }
                urlBuilder.deleteCharAt(urlBuilder.length() - 1); // 删除最后一个&
            }
            // 创建连接
            URL requestUrl = new URL(urlBuilder.toString());
            boolean isHttps = url.toLowerCase().startsWith("https");
            // 根据协议类型创建连接
            if (isHttps) {
                conn = (HttpsURLConnection) requestUrl.openConnection();
            } else {
                conn = (HttpURLConnection) requestUrl.openConnection();
            }
            // 设置请求属性
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Accept", "application/json");
            // 设置超时时间
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            // 获取响应码
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("HTTP请求失败,响应码: " + responseCode);
            }
            // 读取响应
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return response.toString();
    }