How to do a POST using Apache HttpClient over SSL or HTTPS?

Doing a post over HTTP is straight forward task with Apache HttpClient. But HttpClient need some tweaking to work with SSL.

First step is to create your own SSL socket factory extending org.apache.http.conn.ssl.SSLSocketFactory.

public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public CustomSSLSocketFactory(KeyStore truststore) throws
NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException { }

public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException { }

public X509Certificate[] getAcceptedIssuers() {return null;}
};

sslContext.init(null, new TrustManager[] { tm }, null);
}

@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket,
host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}


Rest of the steps are straight forward, you can create an instance of HttpClient which supports HTTPS:

KeyStore trustStore =
KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));

ClientConnectionManager ccm =
new ThreadSafeClientConnManager(params, registry);

HttpClient client = new DefaultHttpClient(ccm, params);


Now we are ready to test the code, let us POST something to an HTTPS site:

List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("key1", "val1"));
nvps.add(new BasicNameValuePair("key2", "val3"));

HttpPost post =
new HttpPost(new URI("https://sslserver/authorize"));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

responseHandler=new BasicResponseHandler();
String result = client.execute(post, responseHandler);


Simple, isn't it? Was this post helpful? Feel free to drop your comments here.

Also Read Reliable Java / Tomcat / JSP / Servlet Hosting

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to our feed and get articles like this delivered automatically to your feed reader? Like our Facebook Page.

Post a Comment (0)
Previous Post Next Post