Httpclient 解决javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException

本文介绍了一种解决在使用HTTPclient-4.5.3.jar进行HTTPS GET请求时出现的javax.net.ssl.SSLHandshakeException异常的方法。通过自定义SSL连接套接字工厂并加载信任材料,可以成功处理SSL握手异常,实现对HTTPS资源的安全访问。

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

1.Httpclient jar 版本:httpclient-4.5.3.jar

2.GET请求抛出异常:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException

3.GET 方法解决异常, 修改GET方法如下:

public String doHttpClientGetRequestForSSL(String request) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient;
        BufferedReader in = null;
        String responseAsString = null;
        try {
            httpclient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())).build();
            HttpUriRequest httpGet = new HttpGet(request);
            CloseableHttpResponse response = httpclient.execute(httpGet);
//            System.out.println(response.getStatusLine());
            responseAsString = EntityUtils.toString(response.getEntity());
//            System.out.println(responseAsString);
            response.close();
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return responseAsString;
    }

引用:HTTP Status 500 - javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find ... 引用:Java Spring应用发送数据报如下问题。 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 原因分析: 引用:httpclient访问https资源时,会出现异常,与环境也有关系,有些机器请求正常。 解决方案: 在HTTPS通信中,当Java程序尝试与服务端建立安全连接时,会进行SSL握手过程。如果在握手过程中出现异常javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException,可能是由于证书验证失败导致的。这种异常通常有两种原因:一是服务端证书不被信任,二是客户端无法找到合适的证书链。 解决这个问题的方法有以下几种: 1. 信任自签名证书:可以通过自定义TrustManager来信任自签名的证书。但这种方法存在安全风险,因为所有的自签名证书都会被信任。 2. 导入服务端证书:可以将服务端的证书导入到Java的信任证书库中,以确保它被信任。可以使用keytool工具将证书导入到Java信任库中。 3. 禁用证书验证:在开发环境中,可以禁用证书验证来避免这个问题。但在生产环境中不建议这样做,因为会降低通信的安全性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值