• resttemplate 调用https 出错 unable to find valid certification path to requested target


    resttemplate 调用https使用下面代码:

    @Bean
    @Primary
    public RestTemplate restTemplate(ClientHttpRequestFactory httpRequestFactory) {
    return new RestTemplate(httpRequestFactory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    //单位为ms
    factory.setReadTimeout(10 * 1000);
    //单位为ms
    factory.setConnectTimeout(30 * 1000);
    return factory;
    }
    调用没有证书的https出现的错误

    org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://gateway.fat.demo.com/service-commodity/providerInventory/queryInventory": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is 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

    修改为下面的java代码后,一切OK:

    @Primary
    @Bean
    public RestTemplate restTemplate() {
    return new RestTemplate(generateHttpsRequestFactory());
    }

    public HttpComponentsClientHttpRequestFactory generateHttpsRequestFactory() {
    try {
    TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory connectionSocketFactory =
    new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(httpClient);
    factory.setConnectTimeout(10 * 1000);
    factory.setReadTimeout(30 * 1000);
    return factory;
    } catch (Exception e) {
    log.error("创建HttpsRestTemplate失败", e);
    throw new RuntimeException("创建HttpsRestTemplate失败", e);
    }

    }

  • 相关阅读:
    Linux CentOS 安装 宝塔
    Linux CentOS 基本命令
    Linux CentOS 各个版本的区别
    OSI物理层之数据通信基础知识
    如何在集群里服役新节点、退役旧节点(DataNode)
    MapReduce的运行流程概述
    MapReduce计算框架的核心编程思想
    解决HDFS上小文件的存储
    计算机网络体系架构之OSI七层模型、TCP/IP四层模型
    集群里常见进程的端口号
  • 原文地址:https://www.cnblogs.com/exmyth/p/15815877.html
Copyright © 2020-2023  润新知