KeanHo Leong
KeanHo Leong

Reputation: 77

getting unable to find valid certification path to requested target calling an https public api

I am trying to use RestTemplate to call a public api from a bank to get exchange rate.

https://api.bnm.gov.my/public/exchange-rate/USD/date/2020-06-25?session=1700&quote=rm

but when i invoked it via eclipse sts, i am getting the error:

Caused by: 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

please help.

but its fine when i use postman ...

Upvotes: 0

Views: 2030

Answers (2)

KeanHo Leong
KeanHo Leong

Reputation: 77

thanks for the response. i have managed to overcome the issue by setting the trust to the URL.

here is the code:

    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;

Upvotes: 0

Erez Ben Harush
Erez Ben Harush

Reputation: 855

The certificate needs to be added to the ssl store: How to import a .cer certificate into a java keystore? Or you can ignore the ssl check: https://stackoverflow.com/a/5189966/5698534

Upvotes: 1

Related Questions