https请求第三方数据,如何忽略掉ssl校验?

本文介绍了一种在Java中请求第三方接口时忽略SSL校验的方法,通过构建自定义的SSL连接套接字工厂和HTTP客户端,实现对HTTPS请求的SSL证书的忽略,适用于需要绕过SSL验证的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在请求第三方接口时,有时会出现ssl的校验,下面我们用Java为例:如何去忽略调ssl校验

  1. 用以下方式构建httpPost
   public static String doPostBaiRong(String url, String str, String charset) {
        HttpPost httpPost = null;
        String result = null;
        final SSLConnectionSocketFactory sslsf;
        try {
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslsf)
                .build();
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(100);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .build();
    
        try {
            //httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            //httpPost.addHeader("Content-Type", "application/x-www-form-urlencode");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000 * 3).build();
            httpPost.setConfig(requestConfig);

            StringEntity se = new StringEntity(str, charset);
            se.setContentType("text/json");
            se.setContentEncoding("UTF-8");
            httpPost.setEntity(se);
            /*HttpResponse response = httpClient.execute(httpPost);*/
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

这种方式可以请求成功

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值