post 请求工具类
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
@Slf4j
public class PostRequestUtils {
public PostRequestUtils() {
}
/**
* 发送POST请求并返回结果
*
* @param proxyAddress 代理服务器地址
* @param proxyPort 代理服务器端口
* @param postUrl 请求URL
* @param data 请求数据
* @return 返回结果
* @throws Exception 抛出异常
*/
public String sendMsg(String proxyAddress, String proxyPort, String postUrl, String data) throws Exception {
PrintWriter out = null;
BufferedReader reader = null;
String result = null;
String returnCode = null;
try {
if (data != null && !data.isEmpty()) {
// 创建连接
URL url = new URL(postUrl);
// 忽略证书校验
ignoreSsl(postUrl);
// 设置代理
HttpURLConnection connection = createConnection(url, proxyAddress, proxyPort);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
// POST请求
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8), true);
out.write(data);
out.flush();
out.close();
// 从HTTP取得返回结果
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
returnCode = parseReturnMsg(sb.toString());
log.info("接口返回:" + returnCode);
reader.close();
// 断开连接
connection.disconnect();
}
} catch (IOException e) {
log.error("发生异常: {}", e.getMessage(), e);
} finally {
closeQuietly(out);
closeQuietly(reader);
}
return returnCode;
}
/**
* 解析返回的消息
*
* @param jsonData JSON格式的返回数据
* @return 解析后的结果
*/
public String parseReturnMsg(String jsonData) {
try {
log.info("接收到的JSON数据: {}", jsonData);
JSONObject jsonObject = JSONObject.parseObject(jsonData);
JSONObject result = jsonObject.getJSONObject("result");
return result.getString("code");
} catch (Exception e) {
log.error("解析JSON数据时发生异常: {}", e.getMessage(), e);
}
return null;
}
/**
* 读取输入流并返回字节数组
*
* @param inStream 输入流
* @return 字节数组
* @throws Exception 抛出异常
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return outStream.toByteArray();
} finally {
inStream.close();
}
}
/**
* 忽略SSL证书校验
*
* @param postUrl 请求URL
* @throws Exception 抛出异常
*/
public static void ignoreSsl(String postUrl) throws Exception {
HostnameVerifier hv = (url, session) -> {
log.warn("警告: URL Host: {} vs. {}", url, session.getPeerHost());
return true;
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
/**
* 信任所有HTTPS证书
*
* @throws Exception 抛出异常
*/
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{new miTM()};
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
/**
* 自定义信任管理器
*/
static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 请求URL
* @return 返回结果
*/
public static String get(String url) {
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 创建代理服务器
InetSocketAddress addr = new InetSocketAddress("10.12.129.9", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // HTTP代理
// 不使用代理
URLConnection connection = realUrl.openConnection();
// 使用代理
// URLConnection connection = realUrl.openConnection(proxy);
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;");
// 建立实际的连接
connection.connect();
// 读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
return result.toString();
} catch (Exception e) {
log.error("发生异常: {}", e.getMessage(), e);
} finally {
closeQuietly(in);
}
return "";
}
/**
* 关闭PrintWriter,忽略关闭时的异常
*
* @param out PrintWriter对象
*/
private static void closeQuietly(PrintWriter out) {
if (out != null) {
try {
out.close();
} catch (Exception ignored) {
}
}
}
/**
* 关闭BufferedReader,忽略关闭时的异常
*
* @param reader BufferedReader对象
*/
private static void closeQuietly(BufferedReader reader) {
if (reader != null) {
try {
reader.close();
} catch (Exception ignored) {
}
}
}
/**
* 创建HTTP连接
*
* @param url 请求URL
* @param proxyAddress 代理服务器地址
* @param proxyPort 代理服务器端口
* @return HttpURLConnection对象
* @throws IOException 抛出IO异常
*/
private static HttpURLConnection createConnection(URL url, String proxyAddress, String proxyPort) throws IOException {
if (proxyPort == null || Integer.parseInt(proxyPort) == 0) {
return (HttpURLConnection) url.openConnection();
} else {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, Integer.parseInt(proxyPort)));
return (HttpURLConnection) url.openConnection(proxy);
}
}
}