Skip to main content

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

Comments

Popular posts from this blog

HDFC Bank introduces Missed Call Service to know Account Balance

Missed call is a powerful business tool in developing countries like India where customers give a miss call to specific phone numbers for getting account details, providing feedback, voting etc. On receiving a missed call from a registered phone number, the underlying app performs a phone number lookup and sends the data to the caller via text message(SMS) or records the call details for future processing.HDFC Bank recently introduced missed call service for its retail customers which allows to retrieve bank account details, mini statement etc. by simply giving a miss call to their toll free numbers.Following services are now available: 1800 270 3333 - Account Balance 1800 270 3355 - Mini Statement 1800 270 3366 - Request for new Cheque Book 1800 270 3377 - Request for Bank account statement Also you can download HDFC Mobile Banking Application by giving a missed call to : 1800 270 3344. Other banks providing missed call serviceAxis bank(known as Axis Dial) - 09225892258Bank of India…

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

Are you searching for Induction Cook-top error codes? Here you can find the error codes of all popular induction cooktops and how to troubleshoot it.

These are for your reference only, do not try to open your cooktop without proper safety measures, we advise you to call the service person if any servicing is needed.

If you want to know how Induction Cook-top works, read our previous article titled What is Induction Cooker? How Induction Cooker Works?.

Whirlpool Induction Cooker Error CodesError CodeErrorSolutionF0An internal error was detected.Disconnect power. Wait 5 seconds before reconnecting power. If the symbol appears again, call for service.F2The surface cooking area is too hot and has turned off.Remove the pans from the surface cooking area. "F2" will disappear when the surface cooking area has cooled. If you turn the surface cooking area back on and "F2" reappears, the cooktop is still too hot. Turn off the surface cooking area and allow it to cool.F4The po…

LICHFL - Generating Home Loan Statements Online

Generating an online statement from LIC Housing Finance Ltd is very easy, simply follow the below steps to create an online account with LICHFL and generate statements online! You may use the online generated statement as a proof for principal paid for a housing loan(under section 80C) and interest paid(under section 24) while filing income tax returns.* Want to know how to save maximum income tax? Read our most read article how to save maximum income tax (opens in new tab).* Paying high interest to LICHFL? Learn how to reduce interest on your existing home loan (opens in new tab).
Before reading further, make sure you have the following information with you: Your Loan Account NumberSanctioned AmountStep 1 - Open LICHFL websiteVisit LICHFL website and click on the 'New Customers? Click Here' link(refer the below screenshot). Step 2 - Enter your loan account detailsFill in the following details: New Loan NumberSanctioned AmountDate of BirthSecurity Codeand click on the Submit b…