From f9e8e4e11ae48da6bf29a2db2c8ba396ca34eb97 Mon Sep 17 00:00:00 2001 From: xuxueli <931591021@qq.com> Date: Sat, 21 Dec 2024 19:07:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(net):=20=E6=B7=BB=E5=8A=A0=20HttpTool=20?= =?UTF-8?q?=E7=B1=BB=E5=B9=B6=E5=AE=9E=E7=8E=B0=20POST=20=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 HttpTool 类,提供 HTTP POST 请求的工具方法 - 实现了对 HTTPS 的支持,并添加了信任所有主机的功能 - 添加了请求头和请求体的处理 - 编写了单元测试用例,验证 HTTP 请求功能 --- src/main/java/com/xxl/tool/net/HttpTool.java | 171 ++++++++++++++++++ .../xxl/tool/test/json/BasicJsonToolTest.java | 4 +- .../com/xxl/tool/test/net/HttpToolTest.java | 17 ++ 3 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/xxl/tool/net/HttpTool.java create mode 100644 src/test/java/com/xxl/tool/test/net/HttpToolTest.java diff --git a/src/main/java/com/xxl/tool/net/HttpTool.java b/src/main/java/com/xxl/tool/net/HttpTool.java new file mode 100644 index 0000000..f928cce --- /dev/null +++ b/src/main/java/com/xxl/tool/net/HttpTool.java @@ -0,0 +1,171 @@ +package com.xxl.tool.net; + +import com.xxl.tool.core.MapTool; +import com.xxl.tool.core.StringTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; + +/** + * @author xuxueli 2018-11-25 00:55:31 + */ +public class HttpTool { + private static Logger logger = LoggerFactory.getLogger(HttpTool.class); + + + // trust-https start + private static void trustAllHosts(HttpsURLConnection connection) { + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + SSLSocketFactory newFactory = sc.getSocketFactory(); + + connection.setSSLSocketFactory(newFactory); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + connection.setHostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + } + private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + }}; + // trust-https end + + + // ---------------------- tool ---------------------- + + /** + * post + * + * @param url + * @param requestBody + * @param timeout + * @return + */ + public static String postBody(String url, + String requestBody, + int timeout) { + return postBody(url, requestBody, null, timeout); + } + + /** + * post + * + * @param url + * @param requestBody + * @param headers + * @param timeout + * @return + */ + public static String postBody(String url, + String requestBody, + Map headers, + int timeout) { + + HttpURLConnection connection = null; + BufferedReader bufferedReader = null; + try { + // connection + URL realUrl = new URL(url); + connection = (HttpURLConnection) realUrl.openConnection(); + + // trust-https + boolean useHttps = url.startsWith("https"); + if (useHttps) { + HttpsURLConnection https = (HttpsURLConnection) connection; + trustAllHosts(https); + } + + // connection setting + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setUseCaches(false); + connection.setReadTimeout(timeout * 1000); + connection.setConnectTimeout(3 * 1000); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); + connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8"); + + // header setting + if(MapTool.isNotEmpty(headers)){ + for (String key : headers.keySet()) { + connection.setRequestProperty(key, headers.get(key)); + } + } + + // do connection + connection.connect(); + + // write requestBody + if (StringTool.isNotBlank(requestBody)) { + DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); + dataOutputStream.write(requestBody.getBytes("UTF-8")); + dataOutputStream.flush(); + dataOutputStream.close(); + } + + /*byte[] requestBodyBytes = requestBody.getBytes("UTF-8"); + connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length)); + OutputStream outwritestream = connection.getOutputStream(); + outwritestream.write(requestBodyBytes); + outwritestream.flush(); + outwritestream.close();*/ + + // valid StatusCode + int statusCode = connection.getResponseCode(); + if (statusCode != 200) { + throw new RuntimeException("StatusCode("+ statusCode +") invalid. for url : " + url); + } + + // result + bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); + StringBuilder result = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + result.append(line); + } + String responseBody = result.toString(); + + // parse returnT + return responseBody; + } catch (Exception e) { + throw new RuntimeException("Http Request Error ("+ e.getMessage() +"). for url : " + url); + } finally { + try { + if (bufferedReader != null) { + bufferedReader.close(); + } + if (connection != null) { + connection.disconnect(); + } + } catch (Exception e2) { + logger.error(e2.getMessage(), e2); + } + } + } + +} diff --git a/src/test/java/com/xxl/tool/test/json/BasicJsonToolTest.java b/src/test/java/com/xxl/tool/test/json/BasicJsonToolTest.java index 986eb7e..62ff743 100644 --- a/src/test/java/com/xxl/tool/test/json/BasicJsonToolTest.java +++ b/src/test/java/com/xxl/tool/test/json/BasicJsonToolTest.java @@ -1,6 +1,7 @@ package com.xxl.tool.test.json; import com.xxl.tool.json.BasicJsonTool; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; @@ -8,7 +9,8 @@ public class BasicJsonToolTest { - public static void main(String[] args) { + @Test + public void test() { Map result = new HashMap<>(); result.put("int", 200); result.put("str", "success"); diff --git a/src/test/java/com/xxl/tool/test/net/HttpToolTest.java b/src/test/java/com/xxl/tool/test/net/HttpToolTest.java new file mode 100644 index 0000000..edbf592 --- /dev/null +++ b/src/test/java/com/xxl/tool/test/net/HttpToolTest.java @@ -0,0 +1,17 @@ +package com.xxl.tool.test.net; + +import com.xxl.tool.net.HttpTool; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpToolTest { + private static final Logger logger = LoggerFactory.getLogger(HttpToolTest.class); + + @Test + public void test() { + String resp = HttpTool.postBody("http://www.baidu.com/", "hello world", 3000); + logger.info(resp); + } + +}