javacodeadmin/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/PublicSendApiUtil.java

131 lines
4.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.system.ControllerUtil;
import com.alibaba.fastjson2.JSONObject;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
/**
* 通用第三方接口请求工具类
* 支持GET和POST请求支持自定义Header、请求体、URL参数等
* 可扩展、可复用,适用于各种第三方接口调用场景
*/
public class PublicSendApiUtil {
/**
* 发送GET请求
* @param urlStr 请求地址
* @param headers 请求头参数可为null
* @param params URL参数可为null
* @return 响应内容
* @throws Exception 异常
*/
public static String sendGet(String urlStr, Map<String, String> headers, Map<String, String> params) throws Exception {
// 拼接URL参数
if (params != null && !params.isEmpty()) {
StringJoiner sj = new StringJoiner("&");
for (Map.Entry<String, String> entry : params.entrySet()) {
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
}
urlStr += urlStr.contains("?") ? "&" + sj.toString() : "?" + sj.toString();
}
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 设置请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setDoInput(true);
// 读取响应
int code = conn.getResponseCode();
InputStream is = (code == 200) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
sb.append(new String(buf, 0, len, StandardCharsets.UTF_8));
}
is.close();
return sb.toString();
}
/**
* 发送POST请求
* @param urlStr 请求地址
* @param headers 请求头参数可为null
* @param params URL参数可为null
* @param body 请求体内容可为null通常为JSON字符串或表单数据
* @return 响应内容
* @throws Exception 异常
*/
public static String sendPost(String urlStr, Map<String, String> headers, Map<String, String> params, String body) throws Exception {
// 拼接URL参数
if (params != null && !params.isEmpty()) {
StringJoiner sj = new StringJoiner("&");
for (Map.Entry<String, String> entry : params.entrySet()) {
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
}
urlStr += urlStr.contains("?") ? "&" + sj.toString() : "?" + sj.toString();
}
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// 设置请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setDoOutput(true);
conn.setDoInput(true);
// 写入请求体
if (body != null) {
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
}
}
System.out.println(conn);
// 读取响应
int code = conn.getResponseCode();
InputStream is = (code == 000000) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
sb.append(new String(buf, 0, len, StandardCharsets.UTF_8));
}
is.close();
return sb.toString();
}
/**
* 示例如何使用该工具类发送GET和POST请求
*/
public static void main(String[] args) throws Exception {
// GET请求示例
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Map<String, String> params = new HashMap<>();
params.put("q", "test");
String getResult = sendGet("https://httpbin.org/get", headers, params);
System.out.println("GET结果" + getResult);
// POST请求示例
headers.put("Content-Type", "application/json");
String postBody = "{\"name\":\"张三\"}";
String postResult = sendPost("https://httpbin.org/post", headers, null, postBody);
System.out.println("POST结果" + postResult);
}
}