java实现https请求的工具类

java实现https请求的工具类,第1张

使用绕过证书方式,复制即可使用;验证证书需配置证书文件。

/**
 * @author CSDN zuimol
*/

public class HttpsUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);

    public static String post(String url, JSONObject content) throws Exception {
        String returnInfo = "";
        CloseableHttpResponse response = null;
        //getTrust():进行证书验证;allTrust:绕过证书验证
        PoolingHttpClientConnectionManager connectionManager = getTrust();
        try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) {
            HttpPost post = new HttpPost(url);
            //指定报文头
            post.setHeader("Context-Type", "application/json;charset=UTF-8");
            //设置entity
            StringEntity entity = new StringEntity(JSONObject.toJSONString(content), "UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);
            //发送请求
            response = client.execute(post);
            logger.info("response->:{}", response);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                returnInfo = EntityUtils.toString(resEntity, "UTF-8");
            }
            EntityUtils.consume(resEntity);
            response.close();
            return returnInfo;
        } catch (IOException | ParseException e) {
            CommonUtil.errorLogs(logger, e);
            return returnInfo;
        }

    }

    /**
     * 绕过验证
     *
     * @author CSDN zuimol
     * @return PoolingHttpClientConnectionManager
     */
    public static PoolingHttpClientConnectionManager allTrust() {
        SSLContext sslContext = null;

        PoolingHttpClientConnectionManager connectionManager = null;
        try {
            sslContext = SSLContext.getInstance("SSLv3");
            X509TrustManager 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];
                }
            };
            sslContext.init(null, new TrustManager[]{trustManager}, null);

            //设置http和https对应处理socket链接工厂的对象
            Registry registry = RegistryBuilder.create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                    .build();
            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            CommonUtil.errorLogs(logger,e);
        }

        return connectionManager;
    }

    /**
     * 进行证书验证
     *
     * @author CSDN zuimol
     * @return PoolingHttpClientConnectionManager
     */
    public static PoolingHttpClientConnectionManager getTrust() {
        PoolingHttpClientConnectionManager connectionManager = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("x.509");
            //证书路径
            ClassPathResource classPathResource = new ClassPathResource("xx.pem");
            Certificate certificate = certificateFactory.generateCertificate(classPathResource.getInputStream());
            //creat TrustStore
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(null ,null);
            //Add certificate
            keyStore.setCertificateEntry("key",certificate);
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            //creatSSlContext
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null,trustManagerFactory.getTrustManagers(),null);
            //设置http和https对应处理socket链接工厂的对象
            Registry registry = RegistryBuilder.create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslContext))
                    .build();
            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
            CommonUtil.errorLogs(logger,e);
        }

        return connectionManager;
    }

}

2022.5.9.新编,无过时方法 。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/889716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存