Skip to content

Instantly share code, notes, and snippets.

@jdhoek
Created November 2, 2014 18:49
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jdhoek/192a965fc63f459b2bee to your computer and use it in GitHub Desktop.
Save jdhoek/192a965fc63f459b2bee to your computer and use it in GitHub Desktop.
Apache HttpComponents httpclient: connect to client-side SSL secured server
package org.example.test;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
/**
* Demonstrate connecting to a server secured with client-side SSL certificates.
*/
public class ConnectIT {
/**
* Path to your client-side SSL certificate in the PKCS12 format, as generated by OpenSSL.
*/
final String KEY_STORE_PATH = "/path/to/pkcs12file.p12";
/**
* PKCS12 file passphrase.
*/
final String KEY_STORE_PASSWORD = "correct horse battery staple";
/**
* URL to connect to. That is, a server for which the above certificate is required.
*/
final String URL = "https://secure.example.org";
@Test
public void sslConnect() throws KeyStoreException, IOException, CertificateException,
NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
// Load the key store, containing the client-side certificate.
KeyStore keyStore = KeyStore.getInstance("pkcs12");
InputStream keyStoreInput = new FileInputStream(KEY_STORE_PATH);
keyStore.load(keyStoreInput, KEY_STORE_PASSWORD.toCharArray());
System.out.println("Key store has " + keyStore.size() + " keys");
// Create an SSL context with our private key store.
// We are only loading the key-material here, but if your server uses a self-signed certificate,
// you will need to load the trust-material (a JKS key-store containing the server's public SSL
// certificate) as well.
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, KEY_STORE_PASSWORD.toCharArray())
.useTLS()
.build();
// Prepare the HTTPClient.
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnectionFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
// Perform a sample HTTP request.
try (CloseableHttpClient httpClient = builder.build()) {
HttpGet httpget = new HttpGet(URL);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.printf(EntityUtils.toString(entity));
}
EntityUtils.consume(entity);
}
}
}
}
@jdhoek
Copy link
Author

jdhoek commented Nov 2, 2014

Depends on HttpComponents httpclient 4.3.5:

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.5</version>
    </dependency>

@varmarakesh
Copy link

Thank you very much, this snippet saved me many hours. I was able to implement httpclient for a rest api that needed ssl certificate. The dependency i used is:

org.apache.httpcomponents httpclient 4.5.1

@jdhoek
Copy link
Author

jdhoek commented Feb 8, 2016

@varmarakesh You're welcome!

@jvmops
Copy link

jvmops commented Aug 24, 2017

Good job my friend 👍

@nephyst
Copy link

nephyst commented Jan 19, 2018

This was so insanely helpful.

@cristianmiranda
Copy link

Nice! 🎉

@Juergen-Seliger
Copy link

Is this example also working with a JKS keystore from JDK 1.7?

@jdhoek
Copy link
Author

jdhoek commented Jun 14, 2023

@Juergen-Seliger I have no idea. It is nine years old, so there is a good chance it will. I know it worked on Java 8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment