Friday, January 1, 2010

Creating an HTTP Client Example

Hey everyone,

To conclude my series of examples on working with HTTP/web based Android programming, I thought I would include an example on how to set up a working HTTP Client that will allow you to do all of your POST/GET calls or whatever it is you might be looking to do. So here it is!

public DefaultHttpClient getClient() { DefaultHttpClient ret = null; //sets up parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); //registers schemes for both http and https SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); ret = new DefaultHttpClient(manager, params); return ret; }

So yes, if you ever encounter any annoying log errors saying things like “HTTPS SSL ERROR”, then it probably has something to do with how your HTTP Client is set up, and in my experience the example above works well in most cases!

Happy New Year! And Happy coding.

- jwei

[Via http://thinkandroid.wordpress.com]

No comments:

Post a Comment