0

I tried to accept my certificate to test my REST api. For that, I tried :

SSLContext sslcontext = SSLContexts
        .custom()
        .loadTrustMaterial(new File(KEYSTORE_PATH), KEYSTORE_PASSWORD,
                new TrustSelfSignedStrategy()).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext, new String[] { "TLSv1" }, null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier());

CloseableHttpClient closeableHttpClient = HttpClients.custom()
        .setSSLSocketFactory(sslsf)
        .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
try {
    HttpPost postRequest = new HttpPost(BASE_URL);

    CloseableHttpResponse response = closeableHttpClient
            .execute(postRequest);
    // try {
    HttpEntity entity = response.getEntity();

    EntityUtils.consume(entity);
    // } finally {
    // response.close();
    // }
} finally {
    closeableHttpClient.close();
}

The error happen when I do closeableHttpClient.execute(postRequest);

Variables are :

private static final String KEYSTORE_PATH = System.getProperty("java.home")
        + "/lib/security/cacerts".replace('/', File.separatorChar);
private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();
private static final String BASE_URL = "http://localhost:9010/api";

note : I do not have a domain name, i'm on localhost. If I understood the error well it's my SSLConnectionSocketFactory closed too early. But I don't know how and why.

EDIT : I'm using HTTPClient. If I update the port HTTP to HTTPS, I receive another error : javax.net.ssl.SSLPeerUnverifiedException: Host name 'localhost' does not match the certificate subject provided by the peer

Bob
  • 529
  • 1
  • 7
  • 28

1 Answers1

0

I found the solution here : javax.net.ssl.SSLPeerUnverifiedException: Host name does not match the certificate subject provided by the peer My code is now :

SSLContext sslcontext = SSLContexts
        .custom()
        .loadTrustMaterial(new File(KEYSTORE_PATH), KEYSTORE_PASSWORD,
                new TrustSelfSignedStrategy()).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext, NoopHostnameVerifier.INSTANCE);

final Registry<ConnectionSocketFactory> registry = RegistryBuilder
        .<ConnectionSocketFactory> create()
        .register("http", new PlainConnectionSocketFactory())
        .register("https", sslsf).build();

final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
        registry);
cm.setMaxTotal(100);

It's working but I'm still working on it (understand and find if I can do something else/better)! Thanks

Community
  • 1
  • 1
Bob
  • 529
  • 1
  • 7
  • 28