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


resttemplate 调用https使用下面代码:

  1.  
    @Bean
  2.  
    @Primary
  3.  
    public RestTemplate restTemplate(ClientHttpRequestFactory httpRequestFactory) {
  4.  
    return new RestTemplate(httpRequestFactory);
  5.  
    }
  6.  
     
  7.  
    @Bean
  8.  
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
  9.  
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  10.  
    //单位为ms
  11.  
    factory.setReadTimeout( 10 * 1000);
  12.  
    //单位为ms
  13.  
    factory.setConnectTimeout( 30 * 1000);
  14.  
    return factory;
  15.  
    }

调用没有证书的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:

  1.  
    @Primary
  2.  
    @Bean
  3.  
    public RestTemplate restTemplate() {
  4.  
    return new RestTemplate(generateHttpsRequestFactory());
  5.  
    }
  6.  
     
  7.  
    public HttpComponentsClientHttpRequestFactory generateHttpsRequestFactory() {
  8.  
    try {
  9.  
    TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
  10.  
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial( null, acceptingTrustStrategy).build();
  11.  
    SSLConnectionSocketFactory connectionSocketFactory =
  12.  
    new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
  13.  
     
  14.  
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
  15.  
    httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
  16.  
    CloseableHttpClient httpClient = httpClientBuilder.build();
  17.  
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
  18.  
    factory.setHttpClient(httpClient);
  19.  
    factory.setConnectTimeout( 10 * 1000);
  20.  
    factory.setReadTimeout( 30 * 1000);
  21.  
    return factory;
  22.  
    } catch (Exception e) {
  23.  
    log.error( "创建HttpsRestTemplate失败", e);
  24.  
    throw new RuntimeException("创建HttpsRestTemplate失败", e);
  25.  
    }
  26.  
     
  27.  
    }
  28.  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM