Skip to content

Instantly share code, notes, and snippets.

@martinhynar
Last active August 29, 2015 14:20
Show Gist options
  • Save martinhynar/06ec843655df89c9d852 to your computer and use it in GitHub Desktop.
Save martinhynar/06ec843655df89c9d852 to your computer and use it in GitHub Desktop.
public DefaultHttpClient createHttpClient() throws Exception {
// Some constants
final int timeout = 10000;
final int HTTP_PORT = 80;
final int HTTPS_PORT = 443;
final String HTTPS = "https";
final String HTTP = "http";
String keystoreName = "keystore";
String keystoreType = "JKS";
String keystorePass = "secret";
String truststoreName = "truststore";
String truststoreType = "JKS";
String truststorePass = "secret";
// we need passwords as character arrays
final char[] keystorePassword = keystorePass.toCharArray();
final char[] truststorePassword = truststorePass.toCharArray();
// Setup the stores first
// Key store
KeyStore keystore = KeyStore.getInstance(keystoreType);
FileInputStream instream = new FileInputStream(keystoreName);
keystore.load(instream, keystorePassword);
instream.close();
// Trust store
KeyStore truststore = KeyStore.getInstance(truststoreType);
instream = new FileInputStream(new File(truststoreName));
truststore.load(instream, truststorePassword);
instream.close();
// Create SSL socket factory that uses the stores
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keystore, new String(keystorePassword), truststore);
// Create container for various parameters, e.g. timeouts
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
// create scheme registry for HTTP and HTTPS
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme(HTTP, PlainSocketFactory.getSocketFactory(), HTTP_PORT));
schemeRegistry.register(new Scheme(HTTPS, sslSocketFactory , HTTPS_PORT));
// Create Connection Manager that takes care of the connections created by the client
ClientConnectionManager httpConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
// Create the desired http client instance
DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager, params);
return httpClient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment