Different ways to access HTTP resources from Android

In this article, I invite the reader to discover the different methods to access http resources from the Android platform.
These methods can be adapted to access web services (using REST) or simply to download files !

First Method : getting an input stream given a simple url from Android using HttpURLConnection

This method is the most basic one : it allows you, using the basic HttpUrlConnection, ( contained in java.net) to get an InputStream from an Url :

You can also use the Post method, sending data in the HTTP POST payload :

But there are better ways to achieve that, using Apache HttpClient, included in android.jar (no need to add another jar, it’s included in android core)

Second Method : getting an input stream given a simple url from Android using HttpClient

Why is it a better to do it ? because the simpler, the better ! See by yourself :

But you maybe wondering if it’s still easy with HTTP Post method ? You won’t be deceived !

But what if you want to read a cookie from the response ? And how can you send a cookie back to the server for the next request ?

Reading / Sending a cookie along with the requests

Using Apache HttpClient, it’s easy to retrieve cookies ! Everything is in the headers after all !

To send a cookie along with your request, keep it simple :

What about the resulting InputStream ? You definitely want to transform it into a String or an Drawable (to set it to an ImageView for example !) don’t you ?

Converting the InputStream into a Drawable in Android

The Drawable class already handles that for you :

Converting the InputStream into a String in Android

This is some classic java stuff (don’t tell about how easier it is in Ruby.. I know :-( … but hey ! Java SE7 at the rescue with NIO !!! maybe one day in 2010 ! )