无法找到调用 https 公共 api 的请求目标的有效认证路径
Posted
技术标签:
【中文标题】无法找到调用 https 公共 api 的请求目标的有效认证路径【英文标题】:getting unable to find valid certification path to requested target calling an https public api 【发布时间】:2020-10-16 19:41:14 【问题描述】:我正在尝试使用 RestTemplate 从银行调用公共 api 以获取汇率。
https://api.bnm.gov.my/public/exchange-rate/USD/date/2020-06-25?session=1700"e=rm
但是当我通过 eclipse sts 调用它时,我得到了错误:
原因:javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径
请帮忙。
但是当我使用邮递员时它很好......
【问题讨论】:
【参考方案1】:证书需要添加到 ssl 存储: How to import a .cer certificate into a java keystore? 或者您可以忽略 ssl 检查: https://***.com/a/5189966/5698534
【讨论】:
【参考方案2】:感谢您的回复。我已经通过将信任设置为 URL 来克服这个问题。
代码如下:
public static HttpComponentsClientHttpRequestFactory buildCustomRequestFactory(String host, int port)
HttpComponentsClientHttpRequestFactory requestFactory = null;
SSLConnectionSocketFactory sslSocketFactory = null;
SSLContext sslContext = null;
HttpClient httpClient = null;
NoopHostnameVerifier hostNameVerifier = new NoopHostnameVerifier();
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
try
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustAllStrategy()).setProtocol("TLSv1.2").build();
sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostNameVerifier);
clientBuilder.setSSLSocketFactory(sslSocketFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("HTTPS", sslSocketFactory)
.register("HTTP", PlainConnectionSocketFactory.getSocketFactory()).build();
PoolingHttpClientConnectionManager clientConnectionMgr = new PoolingHttpClientConnectionManager(registry);
HttpHost customHttpHost = new HttpHost(host, port);
clientConnectionMgr.setSocketConfig(customHttpHost, SocketConfig.custom().setSoTimeout(3000).build());
httpClient = HttpClients.custom().setConnectionManager(clientConnectionMgr).build();
requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
catch (Exception e)
e.printStackTrace();
return requestFactory;
【讨论】:
以上是关于无法找到调用 https 公共 api 的请求目标的有效认证路径的主要内容,如果未能解决你的问题,请参考以下文章