如何使用带有 ssl 证书的 https 客户端调用 api 表单 java

how to invoke apis form java using https client with ssl certificate

我正在使用 HttpClient 从 java 文件调用 rest api。通过使用它,我可以调用 http api 但不能调用 https api.

调用 httpsapi.

时出现以下错误
**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
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)**

我想使用 CloseableHttpClient 调用 https api。

我有包含私钥的证书文件。 请告诉我如何使用此私钥调用 api.

要使用 https 调用 API,您需要配置 SSLContext 并将其设置为您的 HttpClient。请参考下面的示例代码。这只是示例,您可以以不同的方式加载密钥库和信任库,例如从类路径、表单文件系统等。进行相应的更改。

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    KeyStore identity = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(identity, "password".toCharArray());
    SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
    sslContext.init(
        keyManagerFactory.getKeyManagers(), 
        trustManagerFactory.getTrustManagers(), 
        null
    );
    HttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new DefaultHostnameVerifier())
            .build();