Last active
August 29, 2015 13:58
-
-
Save skempken/9953049 to your computer and use it in GitHub Desktop.
Java class that initializes a HttpClient using X.509-certificate-based client authentication.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.http.client.HttpClient; | |
import org.apache.http.conn.ClientConnectionManager; | |
import org.apache.http.conn.scheme.PlainSocketFactory; | |
import org.apache.http.conn.scheme.Scheme; | |
import org.apache.http.conn.scheme.SchemeRegistry; | |
import org.apache.http.conn.ssl.SSLSocketFactory; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.impl.conn.SingleClientConnManager; | |
import org.apache.http.params.BasicHttpParams; | |
import org.apache.http.params.HttpParams; | |
import javax.net.ssl.KeyManager; | |
import javax.net.ssl.KeyManagerFactory; | |
import javax.net.ssl.SSLContext; | |
import java.security.KeyStore; | |
import java.security.KeyStoreException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.UnrecoverableKeyException; | |
/** | |
* Initializes a HttpClient using X.509-certificate-based client authentication. | |
* @author Sebastian Kempken | |
* | |
*/ | |
public class SslHttpUtil { | |
private static final KeyManager[] getKeyManagersFromKeyStore(KeyStore keyStore, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException | |
{ | |
final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( | |
KeyManagerFactory.getDefaultAlgorithm()); | |
kmfactory.init(keyStore, password); | |
final KeyManager[] kms = kmfactory.getKeyManagers(); | |
return kms; | |
} | |
public static final HttpClient createSslHttpClient(KeyStore keyStore, char[] password) { | |
try | |
{ | |
SSLContext sslcontext = SSLContext.getInstance("TLS"); | |
final KeyManager[] km = getKeyManagersFromKeyStore(keyStore, password); | |
sslcontext.init(km, null, null); | |
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext); | |
Scheme https = new Scheme("https", sslSocketFactory, 443); | |
Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); | |
SchemeRegistry schemeRegistry = new SchemeRegistry(); | |
schemeRegistry.register(http); | |
schemeRegistry.register(https); | |
final HttpParams params = new BasicHttpParams(); | |
ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); | |
return new DefaultHttpClient(cm, params); | |
} | |
catch(Exception exception) | |
{ | |
throw new RuntimeException("Error initializing HttpClient", exception); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment