public List<X509Certificate> extractUntrustedCerts(String host) throws NoSuchAlgorithmException, IOException, KeyManagementException {
        final SSLContext ctx = SSLContext.getInstance("TLS");
        // this trust manager is augmenting the SSLHandshakeException cause, so we can later in the catch block
        // access the certificate chain.
        final X509TrustManager trustManager = new CertificateChainReportingTrustManager(httpClient.x509TrustManager());
        ctx.init(null, new TrustManager[]{trustManager}, new SecureRandom());

        final OkHttpClient reportingClient = httpClient.newBuilder().sslSocketFactory(ctx.getSocketFactory(), trustManager).build();

        final Request req = new Request.Builder().get().url(host).build();
        try(final Response ignored = reportingClient.newCall(req).execute()) {
            // nothing to do here, we are interested only in exceptions
        } catch (SSLHandshakeException e) {
            if (e.getCause() instanceof CertificateReportingException certificateReportingException) {
                return Arrays.asList(certificateReportingException.getChain());
            }
        }
        return Collections.emptyList();
    }
@Test
    void testExtraction() throws NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException, CertificateException {
        final String host = getHttpHost();

        final OkHttpClient client = new OkHttpClient.Builder().build();
        final Request request = new Request.Builder().get().url(host).build();

        // firsr verify that the call to the self-signed server fails
        Assertions.assertThatThrownBy(() -> {
            try (final Response ignored = client.newCall(request).execute()) {
            }
        }).isInstanceOf(SSLHandshakeException.class);

        // extract server certificates
        final UntrustedCertificateExtractor extractor = new UntrustedCertificateExtractor(client);
        final List<X509Certificate> certificates = extractor.extractUntrustedCerts(host);
        // and add them to the truststore configured for this client8
        final OkHttpClient clientWithTrust = clientWithTruststore(client, certificates);

        // now verify the connection again, should work without errors and deliver response
        try (final Response response = clientWithTrust.newCall(request).execute()) {
            Assertions.assertThat(response.body()).isNotNull();
            Assertions.assertThat(response.body().string()).isEqualTo("This is the response");
        }

    }