java爬取HTTPS接口POST请求工具类代码示例
时间: 2023-10-23 20:37:12 浏览: 101
JAVA利用HttpClient进行POST请求(HTTPS)实例
5星 · 资源好评率100%
以下是一个Java爬取HTTPS接口POST请求工具类的代码示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsUtil {
public static String post(String urlStr, Map<String, String> params) throws IOException {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} }, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.setDoOutput(true);
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
sb.deleteCharAt(sb.length() - 1);
conn.getOutputStream().write(sb.toString().getBytes("UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
return result.toString();
}
}
这个工具类使用了Java的HttpsURLConnection类来发送POST请求,并使用SSLContext来解决HTTPS证书验证的问题。在这个示例中,我们简单地使用了一个信任所有证书的X509TrustManager类,并使用了一个信任所有主机名的HostnameVerifier类。在实际应用中,你应该仔细考虑你的证书和主机名验证策略,以确保安全性。
阅读全文