Sunday, December 29, 2013

Android Recipe: Reusable Android Gson HTTP Client

Here's a simple implementation of a reusable HTTP client for android using the AndroidHttpClient. It takes a ton of ugly code to accomplish the simple task of sending HTTP requests in Android so at least you only have to do it in one place. Unfortunately type erasure makes this slightly more difficult because we can't create a pure generic implementation because the unmarshalling code doesn't know what type to use. If you create a generic implementation you won't get compile errors but instead will get nasty runtime errors like:

ClassCastException: java.util.LinkedHashMap cannot be cast to com.your.class.Name

We can get around this by providing a concrete implementation for the unmarshalling code whe we instantiate our HttpClient like so:

Verbose, ugly, and full of boilerplate. Pretty much par for the course for Android code.

There's no error handling to speak of so you need to add that bit in. The way I do it is to throw custom exceptions for whatever kind of error I come across.

No comments:

Post a Comment