@Slf4j
@Component
public class HttpsFacility {
//支持不安全证书的https访问
public String httpsPost(String url ,String json) throws KeyManagementException, NoSuchAlgorithmException, IOException {
SSLContext sc = createSslContext();
HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier((s, sslSession) -> true);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
os.close();
StringBuilder result = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while (null != (line = br.readLine())) {
result.append(line).append("\n");
}
}
conn.disconnect();
log.info(result.toString());
return result.toString();
}
private static SSLContext createSslContext() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new java.security.SecureRandom());
return sc;
}
}
支持不安全证书的https访问
最新推荐文章于 2023-05-15 11:24:50 发布
关键词由CSDN通过智能技术生成