忽略证书的HTTPS请求实现

发布时间 2023-07-24 17:37:10作者: pr1s0n
public static void httpsTest(String httpUrl){
    //忽略证书的https请求
    try {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String result = restTemplate.getForObject(httpUrl, String.class);
        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}