Https and Android:
We all know that we have to secure our web service calls and its very easy to intercept these calls if they are not properly secured. But getting this to work on Android is not that straightforward. After some substantial amount of research I found the easy way to get it working and decided to save some time for my co android developers.
private static int NET_TIMEOUT = 30000;
private static int NETWORK_POOL = 4;
DefaultHttpClient client = getClient(ctx);
HttpGet getRequest = new HttpGet(url);
Instead of instantiating the DefaultHttpClient I implemented my own getClient which would return the custom HttpClient with the SocketFactory enabled.
private static DefaultHttpClient getClient(Context ctx) {
DefaultHttpClient client;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, NET_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, NET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRouteBean(NETWORK_POOL));
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", newSSLSocketFactory(ctx), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, registry);
client = new DefaultHttpClient(cm, httpParams);
return client;
}
registry.register(new Scheme(“https”, newSSLSocketFactory(ctx), 443)); is key here .
private static SSLSocketFactory newSSLSocketFactory(Context ctx)
{
try{
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = ctx.getResources().openRawResource(R.raw.zynglstore);
try{
trusted.load(in,"changeme".toCharArray());
}finally{
in.close();
}
SSLSocketFactory mySslFactory = new SSLSocketFactory(trusted);
return mySslFactory;
}catch(Exception e){
throw new AssertionError(e);
}
}
Then coming back to the original code .
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
Http Post also should work the similar way.
Hope this helps.
I have created the keystore using http://portecle.sourceforge.net/ ..Portcele. This is a very handy tool






