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