Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Created September 19, 2019 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmalex07/03bde75204adbc6ce9d78fa7ea297d58 to your computer and use it in GitHub Desktop.
Save drmalex07/03bde75204adbc6ce9d78fa7ea297d58 to your computer and use it in GitHub Desktop.
An example of using custom SSL context in Apache HttpClient. #https #ssl #apache-httpclient #keystore #certificate

README - SSL context for Apache HttpClient

Load keystore as usual:

KeyStore keystore = KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream("keystore.p12")) {
  keystore.load(in, "secret".toCharArray());
}

Build a custom SSL context:

import javax.net.ssl.SSLContext;
import org.apache.http.ssl.SSLContexts;
...
SSLContext sslContext = SSLContexts.custom()
  // Where is my key/certificate pair?
  .loadKeyMaterial(keystore, keyPassword.toCharArray()) 
  // Where is the list of trusted CA certificates?
  .loadTrustMaterial(keystore, /* use default trust strategy */ null)
  .build();

Build an HTTP client using the former context:

ClosableHttpClient httpClient = HttpClients.custom()
  .setSSLContext(sslContext)
  // .. other configurations ...
  .build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment