复制即用
java
package utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.List;
/**
* @author lpx
* @create 2021-06-28 11:17
* @Description http请求工具类
* @Version 1.0
*/
@Slf4j
@Component
public class HttpSendUtils {
public static String sendHeaderPostWb(String url, String contentType, String param, List<String> headers) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
HttpURLConnection conn = null;
try {
URL realUrl = new URL(url);
boolean isHttps = "https".equalsIgnoreCase(realUrl.getProtocol());
if (isHttps) {
// 创建一个忽略证书验证的SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}}, new java.security.SecureRandom());
// 安装所有的信任管理器(仅用于HTTPS)
// 注意:在实际应用中,不建议这样做,因为它会绕过SSL/TLS的安全验证。
// 这里只是为了演示如何忽略证书验证。
SSLContext.setDefault(sslContext);
// 创建一个HttpsURLConnection对象
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // 接受任何主机名
}
};
conn = (HttpsURLConnection) realUrl.openConnection();
((HttpsURLConnection) conn).setHostnameVerifier(hv);
}else{
conn = (HttpURLConnection) realUrl.openConnection();
}
// 设置通用的请求属性
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if (!headers.isEmpty()) {
for (String header : headers) {
String[] parts = header.split(":");
conn.setRequestProperty(parts[0].trim(), parts[1].trim());
}
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}