package com.ruoyi.other.util.payment.wx;
|
|
import cn.hutool.http.HttpRequest;
|
import cn.hutool.http.HttpResponse;
|
|
import javax.net.ssl.*;
|
import java.io.BufferedReader;
|
import java.io.InputStreamReader;
|
import java.io.OutputStream;
|
import java.net.URL;
|
import java.security.cert.CertificateException;
|
import java.security.cert.X509Certificate;
|
|
/**
|
* HTTP工具类
|
*/
|
public class HttpUtil {
|
|
/**
|
* 发送POST请求
|
*/
|
public static String post(String urlStr, String data) throws Exception {
|
// 设置超时时间(单位:毫秒)
|
int timeout = 5000; // 5秒
|
|
// 发送 POST 请求
|
try (HttpResponse response = HttpRequest.post(urlStr)
|
.body(data, "application/xml") // 设置 XML 请求体
|
.timeout(timeout)
|
.execute()) {
|
|
// 检查 HTTP 状态码
|
if (!response.isOk()) {
|
throw new RuntimeException("HTTP请求失败,状态码: " + response.getStatus()
|
+ ", 响应: " + response.body());
|
}
|
return response.body();
|
}
|
}
|
|
/**
|
* 发送HTTPS请求
|
*/
|
public static String postHttps(String urlStr, String data, String certPath, String certPassword) throws Exception {
|
// 创建SSL上下文
|
SSLContext sslContext = SSLContext.getInstance("SSL");
|
TrustManager[] trustManagers = {new X509TrustManager() {
|
@Override
|
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
}
|
|
@Override
|
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
}
|
|
@Override
|
public X509Certificate[] getAcceptedIssuers() {
|
return null;
|
}
|
}};
|
sslContext.init(null, trustManagers, new java.security.SecureRandom());
|
|
// 创建HTTPS连接
|
URL url = new URL(urlStr);
|
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
|
conn.setSSLSocketFactory(sslContext.getSocketFactory());
|
conn.setHostnameVerifier(new HostnameVerifier() {
|
@Override
|
public boolean verify(String hostname, SSLSession session) {
|
return true;
|
}
|
});
|
|
conn.setRequestMethod("POST");
|
conn.setDoOutput(true);
|
conn.setDoInput(true);
|
conn.setUseCaches(false);
|
conn.setRequestProperty("Content-Type", "application/xml");
|
conn.setRequestProperty("Connection", "Keep-Alive");
|
conn.setRequestProperty("Charset", "UTF-8");
|
|
// 发送请求
|
OutputStream os = conn.getOutputStream();
|
os.write(data.getBytes("UTF-8"));
|
os.flush();
|
os.close();
|
|
// 获取响应
|
StringBuilder result = new StringBuilder();
|
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
String line;
|
while ((line = br.readLine()) != null) {
|
result.append(line);
|
}
|
br.close();
|
|
return result.toString();
|
}
|
}
|