|
@@ -0,0 +1,82 @@
|
|
|
+package cn.ezhizao.common.http;
|
|
|
+
|
|
|
+import cn.hutool.http.HttpRequest;
|
|
|
+import cn.hutool.http.HttpUtil;
|
|
|
+
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+public class HttpClientUtil {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送 GET 请求
|
|
|
+ *
|
|
|
+ * @param url 请求的 URL
|
|
|
+ * @param params 请求参数,以 key=value 形式传递
|
|
|
+ * @return 响应结果
|
|
|
+ */
|
|
|
+ public static String sendGet(String url, Map<String, Object> params) {
|
|
|
+ // 使用 Hutool 的 HttpUtil 发送 GET 请求
|
|
|
+ String result = HttpUtil.get(url, params);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送 POST 请求
|
|
|
+ *
|
|
|
+ * @param url 请求的 URL
|
|
|
+ * @param params 请求参数,以 key=value 形式传递
|
|
|
+ * @return 响应结果
|
|
|
+ */
|
|
|
+ public static String sendPost(String url, Map<String, Object> params) {
|
|
|
+ // 使用 Hutool 的 HttpUtil 发送 POST 请求
|
|
|
+ String result = HttpUtil.post(url, params);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送带自定义头部的 GET 请求
|
|
|
+ *
|
|
|
+ * @param url 请求的 URL
|
|
|
+ * @param params 请求参数,以 key=value 形式传递
|
|
|
+ * @param headers 自定义头部信息
|
|
|
+ * @return 响应结果
|
|
|
+ */
|
|
|
+ public static String sendGetWithHeaders(String url, Map<String, Object> params, Map<String, String> headers) {
|
|
|
+ HttpRequest request = HttpRequest.get(url).form(params);
|
|
|
+ headers.forEach(request::header);
|
|
|
+ return request.execute().body();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发送带自定义头部的 POST 请求
|
|
|
+ *
|
|
|
+ * @param url 请求的 URL
|
|
|
+ * @param params 请求参数,以 key=value 形式传递
|
|
|
+ * @param headers 自定义头部信息
|
|
|
+ * @return 响应结果
|
|
|
+ */
|
|
|
+ public static String sendPostWithHeaders(String url, Map<String, Object> params, Map<String, String> headers) {
|
|
|
+ HttpRequest request = HttpRequest.post(url).form(params);
|
|
|
+ headers.forEach(request::header);
|
|
|
+ return request.execute().body();
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ // 测试 GET 请求
|
|
|
+ String getUrl = "https://jsonplaceholder.typicode.com/posts";
|
|
|
+ Map<String, Object> getParams = new HashMap<>();
|
|
|
+ getParams.put("userId", 1);
|
|
|
+ String getResponse = sendGet(getUrl, getParams);
|
|
|
+ System.out.println("GET Response: " + getResponse);
|
|
|
+
|
|
|
+ // 测试 POST 请求
|
|
|
+ String postUrl = "https://jsonplaceholder.typicode.com/posts";
|
|
|
+ Map<String, Object> postParams = new HashMap<>();
|
|
|
+ postParams.put("title", "foo");
|
|
|
+ postParams.put("body", "bar");
|
|
|
+ postParams.put("userId", 1);
|
|
|
+ String postResponse = sendPost(postUrl, postParams);
|
|
|
+ System.out.println("POST Response: " + postResponse);
|
|
|
+ }
|
|
|
+}
|