java https 工具类_java https 请求工具类-通用
时间: 2023-08-04 22:31:08 浏览: 577
好的,以下是一个Java HTTPS请求的通用工具类示例:
```
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Map;
public class HttpsUtil {
public static String sendPostRequest(String url, Map<String, String> params) throws Exception {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] trustManagers = {new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, new java.security.SecureRandom());
// 打开连接
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
// 设置请求头
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 设置请求参数
String urlParameters = "";
if (params != null && !params.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
urlParameters = sb.toString();
}
// 发送POST请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
这个工具类可以在HTTPS请求中使用,会自动忽略SSL证书验证。使用时只需要调用sendPostRequest方法,传入URL和请求参数即可。
阅读全文