问题:在http请求https接口过程中经常会遇到SSL证书检查或者证书过期

** sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed **
在这里插入图片描述

解决办法:绕过证书检查

代码如下:


public static byte[] getFile(String url) throws  Exception {
        log.info("get file url:"+url);
        try {
            /*HttpClientBuilder builder = HttpClients.custom();
            builder.setSSLHostnameVerifier((hostName, sslSession) -> {
                return true; // 证书校验通过
            });*/
            //CloseableHttpClient httpclient = builder.build();
            //CloseableHttpClient httpclient =  createSSLClientDefault();
            DefaultHttpClient httpclient = new DefaultHttpClient();
            enableSSL(httpclient);
            HttpGet request = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if(entity == null) return null;
                byte[] imgByte = EntityUtils.toByteArray(entity);
                return imgByte;
            }

        }catch (Exception ex){
            log.error("get file error:"+ex.getMessage());
            ex.printStackTrace();
            throw ex;
        }
        return null;
    }
    /**
     * 访问https的网站
     * @param httpclient
     */
    private static void enableSSL(DefaultHttpClient httpclient){
        //调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 重写验证方法,取消检测ssl
     */
    private static TrustManager truseAllManager = new X509TrustManager(){

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    };
};
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐