sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath

背景

  • 使用WxJava开发包上传企微的临时素材库,传入一个url地址,这个url的https证书是使用Let’s Encrypt申请,在conn.getInputStream()报错。

异常详情

  • 代码和报错
        String url = "https://xxx/public/product/2025/05/08/21ca6b1e55d543b09974040f133ab978qlg2hm3ndb.png";
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL remote = new URL(url);
            conn = (HttpURLConnection) remote.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(60 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
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
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
	...省略...

在这里插入图片描述

解决方案

方案一

  • 先导出,一般是crtpem文件
    在这里插入图片描述
keytool -import -keystore  d:/b.jks -storepass 123456 -alias alias_for_certificate -file D:\Download\_.xxxx.crt
  • D:\Download\_.xxxx.crt 是导出的证书路径,123456 是密码,d:/b.jks 是希望生成的信任库文件。
  • 执行命令后输入y
    在这里插入图片描述
  • 加入以下代码
        // 代码放到这里 可以使用相对路径
        System.setProperty("javax.net.ssl.trustStore", "d:/b.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "123456");
  • 运行效果
    在这里插入图片描述

方案二

  • 换一种方式下载文件,刚好项目里引入了hutool,换成hutoolHttpUtil工具类去下载
HttpUtil.downloadFile(url,"D:/");
  • 下载成功
    在这里插入图片描述
    在这里插入图片描述

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值