I am using Apache http client in my Java project.
I am able to load the ssl keystore and truststore for a single route.
Here's the code snippet I am using:
protected void initConnectionManager(HttpClientProps props) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException, CertificateException, IOException {
PoolingHttpClientConnectionManager connectionManager = createConnectionManager(buildRegistry(props));
connectionManager.setMaxTotal(props.getMaxThreadPool());
connectionManager.setDefaultMaxPerRoute(props.getDefaultMaxPerRoute());
setConnManager(connectionManager);
}
protected Registry<ConnectionSocketFactory> buildRegistry(HttpClientProps props) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
final RegistryBuilder<ConnectionSocketFactory> registryBuilder;
if (props.isSslEnabled()) {
final KeyStore ts = getKeyStoreInstance(), ks = getKeyStoreInstance();
ts.load(new FileInputStream(props.getTrustStorePath()), props.getTrustStoreKey().toCharArray());
ks.load(new FileInputStream(props.getKeyStorePath()), props.getKeyStoreKey().toCharArray());
final SSLContext ssl = buildSslContext(props, ts, ks);
final ConnectionSocketFactory sslConnectionFactory = getSslConnectionFactory(ssl);
registryBuilder = createRegistryBuilder(HTTPS, sslConnectionFactory);
} else {
registryBuilder = createRegistryBuilder(HTTP, new PlainConnectionSocketFactory());
}
return registryBuilder.build();
}
protected RegistryBuilder<ConnectionSocketFactory> createRegistryBuilder(String id, ConnectionSocketFactory factory) {
return RegistryBuilder.<ConnectionSocketFactory>create().register(id, factory);
}
protected SSLContext buildSslContext(HttpClientProps props, KeyStore ts, KeyStore ks) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
return SSLContexts.custom()
.loadTrustMaterial(ts, this::getTrustStrategy)
.loadKeyMaterial(ks, props.getKeyStoreKey().toCharArray())
.setSecureRandom(new SecureRandom())
.build();
}
Now I am trying to figure out for multiple routes for example:
If both the routes need different keystore JKS and truststore JKS then how do I set that in the same client and configure it to use keystore1 and truststore1 for route1 and keystore2 and truststore2 for route2?
Or should I use a new object of the httpclient for each route and set the keystore and truststore respectively? [In this approach the catch is a new thread pool will be created for each client. I am trying to avoid it.]