https请求报错unable to find valid certification path to requested target解决

这篇具有很好参考价值的文章主要介绍了https请求报错unable to find valid certification path to requested target解决。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

        在Java项目中请求HTTPS时,可能会遇到 "unable to find valid certification path to requested target" 错误。这个错误通常是由于SSL证书问题引起的。要解决此问题,可以尝试以下方法

1.忽略SSL验证

        OkHttpClient封装请求

public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // 创建一个信任所有证书的TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            // 创建一个不验证证书的 SSLContext,并使用上面的TrustManager初始化
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 使用上面创建的SSLContext创建一个SSLSocketFactory
            javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            builder.readTimeout(1, TimeUnit.MINUTES);

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws Exception {
        
        // 发送请求
        Request request = new Request.Builder()
                .url("https://example.com")
                .build();

        Response response = getUnsafeOkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());
    }
        CloseableHttpClient请求
public static void main(String[] args) throws Exception {
        // 创建SSL上下文,忽略证书验证
        SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);


        // 创建 CloseableHttpClient 对象
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();

        // 创建 HttpGet 对象,并设置请求URL
        HttpGet httpGet = new HttpGet("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg");

        // 设置请求头参数
        httpGet.setHeader("User-Agent", "Mozilla/5.0");

        // 发送请求,获取响应
        HttpResponse response = httpClient.execute(httpGet);

        // 获取响应实体
        HttpEntity entity = response.getEntity();

        // 读取响应内容
        String responseBody = EntityUtils.toString(entity);

        // 输出响应
        System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
        System.out.println("Response Body: " + responseBody);

        // 关闭httpClient
        httpClient.close();
    }

        HttpURLConnection请求

//忽略SSL验证
    public static void ignoreSSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }

    public static void main(String[] args) throws Exception {
        ignoreSSL();
        // 创建URL对象
        URL url = new URL("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg");

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求头参数
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        // 发送请求
        int responseCode = connection.getResponseCode();

        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 输出响应
        System.out.println("Response Code: " + responseCode);
        System.out.println("Response Body: " + response.toString());

        // 关闭连接
        connection.disconnect();
    }

        RestTemplate请求

public static void ignoreSSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {}

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }

    public static void main(String str[]) throws Exception{
        ignoreSSL();
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity("https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg", String.class);
        System.out.println(response.getBody());
    }
2.添加证书到本地证书库
  • 获取证书,首先确保您访问的HTTPS网站具有有效的SSL证书。可以通过浏览器访问该网站并查看并导出证书。

https请求报错unable to find valid certification path to requested target解决,https,网络协议,java

 

  • 导入SSL证书:将SSL证书导入到Java的信任存储库中。可以使用keytool命令行工具执行此操作。运行以下命令将证书导入到默认的JDK信任存储库中文章来源地址https://www.toymoban.com/news/detail-719451.html

  1. keytool -import -alias alias_name -keystore path_to_jdk_cacerts -file path_to_certificate
    
    -- alias_name 证书指定的别名
    -- path_to_jdk_cacerts是JDK信任存储库的路径,默认路径为$JAVA_HOME/jre/lib/security/cacerts,
    -- path_to_certificate是下载的SSL证书的路径

到了这里,关于https请求报错unable to find valid certification path to requested target解决的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 如何解决HTTPS请求报错sun.security.validator.ValidatorException: PKIX path building failed

    在Java中进行网络请求时出现\\\"sun.security.validator.ValidatorException: PKIX path building failed\\\"错误通常是由于SSL证书验证失败引起的。这种错误可能由以下几种原因导致: 1、证书链不完整或证书不受信任: Java使用TrustStore来验证SSL证书的有效性。如果服务器使用的SSL证书不在Java TrustS

    2024年04月13日
    浏览(34)
  • RuntimeError: Unable to find a valid cuDNN algorithm to run convolution

    使用yolov5l模型训练时出现报错,但是昨天使用yolov5s模型时是可以正常训练的。 发生报错的原因是gpu内存占用过高,terminal输入nvidia-smi查看gpu的使用情况。   我们需要把bach_size调小,一般建议是8的倍数,内存不够用时尽量调低,此处我设置成了16。 结果运行正常。 使用yol

    2024年02月11日
    浏览(30)
  • Unable to connect to the server: x509: certificate has expired or is not yet valid

    手动更新所有证书,执行命令 更新用户配置 用更新后的admin.conf替换/root/.kube/config文件 k8s解决证书过期官方文档:https://kubernetes.io/zh-cn/docs/tasks/administer-cluster/kubeadm/kubeadm-certs/ 帮助文档: https://www.cnblogs.com/00986014w/p/13095628.html

    2024年02月04日
    浏览(34)
  • MINIO 配置https报错:x509:cannot validate certificate【已解决】

    为MINIO配置https时,首先按官方要求官网描述(How to secure access to MinIO server with TLS),将TLS的公私钥放到:{{HOME}}/.minio/certs 里。 注意: 私钥需要命名为:private.key 公钥需要命名为:public.crt (如果公钥是以pem格式结尾,可直接改为crt格式) 但配置完成后会遇到如下错误,x509:c

    2024年02月14日
    浏览(34)
  • 已解决unable to access ‘https://github.com/**‘: SSL certificate problem: unable to get

    错误:unable to access \\\'https://github.com/\\\': SSL certificate problem: unable to get local issuer certificate 这个问题是由于没有配置信任的服务器HTTPS验证。默认,curl被设为不信任任何CAS,就是说,它不信任任何服务器验证。 只需要执行下面命令就可以解决:  

    2024年03月19日
    浏览(43)
  • 【bug解决】RuntimeError: Unable to find a valid cuDNN algorithm to run convolution

    进行深度学习的算法模型训练的时候,终端报错: 产生报错的原因可能有两种: 1.模型训练的环境中cudnn,CUDA的版本号不匹配 解决办法:安装对应的cudnn,以及cuda,找到对应的torch框架,进行安装 2.其实问题更加简单,是模型的训练的batch-size训练过大了,调整更小,就可以了

    2024年02月11日
    浏览(39)
  • K8S异常之Unable to connect to the server: x509: certificate has expired or is not yet valid

    2.1 处理步骤 2.2 处理步骤详细情况 如上,发现很多证书都是 invalid 的状态,接着更新证书: 如下,更新证书后,证书过期时间已经更新为 365d 3.1 再次查看kubectl get node,发现有新的错误: error: You must be logged in to the server (Unauthorized) 3.2 上述错误解决方案 备份配置文件 cp -rp

    2024年02月03日
    浏览(35)
  • Git Clone 报错 `SSL certificate problem: unable to get local issuer certificate`

    如果您在尝试克隆Git存储库时得到 “SSL certificate problem: unable to get local issuer certificate” 的错误,这意味着Git无法验证远程存储库的SSL证书。如果SSL证书是自签名的,或者SSL证书链有问题,就会发生这种情况。 想要修复这个错误,可以尝试以下解决方案: 一、 禁用SSL验证: 一般

    2024年02月07日
    浏览(37)
  • 关于picgo图床报错“unable to verify the first certificate“

    关于picgo图床报错\\\"unable to verify the first certificate\\\" 编程上的疑难杂症(一) 问题:本人picgo加github图床上传出现以下问题 \\\"message\\\": \\\"unable to verify the first certificate\\\"(无法验证第一证书) 问题分析: 图床是github图床,工具是picgo,为了可以顺利访问github用到steam++(Watt Toolkit)加速

    2024年02月11日
    浏览(43)
  • Composer出现 SSL certificate problem: unable to get local issuer certificate 报错的解决方法

    Composer出现crul SSL报错的问题是没有安装CA证书导致的!!! 错误信息如下: [ComposerDownloaderTransportException]                                                                                                      curl error 60 while downloading https://repo.packagist.org/package

    2024年02月03日
    浏览(42)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包