天天看點

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);

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

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);

}