Pages

Sunday 27 May 2012

Android HTTP Tutorial

The Android libraries include both the Apache HTTP Client, and the HttpURLConnection class. The Dalvik team is focusing their efforts on the latter, and recommend using it for applications targeting Gingerbread (Android v. 2.3) and beyond.
At the time of writing, nearly three quarters of Android devices are running Gingerbread or later, so this tutorial covers HttpURLConnection.

 

Creating a connection

A common use case will be for an Android app to access a web service, and the sample code accesses the Twitter search API. To retrieve recent Tweets from the user @stephenfry, point a web browser at:

http://search.twitter.com/search.json?q=%stephenfry

The @ symbol is encoded as %40, and the response is a piece of JSON encoding the data for the  Tweets.

A URL object is required to open a HttpURLConnection on an Android device. The simplest method is to pass the complete address in the constructor.

URL url = new URL ("http://search.twitter.com/search.json?q=%40coderscode");

This doesn't allow much flexibility, as any query has to be hard coded. If the parameters can change then a better approach is to use the Uri and Uri.Builder to construct one.

Uri uri = Uri.parse ("http://search.twitter.com/search.json");
Uri.Builder builder = uri.buildUpon ();
builder.appendQueryParameter ("q", "@coderscode");
URL url = new URL (builder.toString ());

The Builder class will escape any symbols, so the generated URL will be properly encoded.

The URL can then be used to create a HttpURLConnection. Note that the connection has to be cast, as the method returns a reference to the base URLConnection type.

HttpURLConnection connection = (HttpURLConnection) url.openConnection ();

Should the URL point at a HTTPS address, then the return type can be optionally cast to a HttpsURLConnection, which provides methods for managing the connection.

Note that the connection is a blocking operation, and must be opened on a separate thread, otherwise the app's UI will freeze. The AsyncTask class provides the simplest mechanism for this.

 

Setting up the connection

The HttpURLConnection can handle the different HTTP verbs.
  • The default verb is GET.
  • To use POST, invoke setDoOutput (true).
  • For other methods (e.g. PUT, DELETE, HEAD, etc.), use setRequestMethod (), passing the appropriate verb as a String. (e.g. connection.setRequestMethod ("PUT"))

 

Using the connection

The HTTP response method and code can be queried by:

String message = connection.getResponseMessage ();
int code = connection.getResponseCode ();

These indicate the same thing, so an expected pair might be a code of 200 and the message OK.

Once a connection has been made, data can be uploaded to a server using the OutputStream, obtained by:

OutputStream output = connection.getOutputStream ();

Similarly, the response body from the server can be accessed using an InputStream.

InputStream input = connection.getInputStream ();

The InputStream can then be wrapped up in an InputStreamReader and BufferedReader, allowing the response to be read back from the server. Using a BufferedReader is recommended since it is more efficient.

BufferedReader reader = new BufferedReader (new InputStreamReader (input));

For a character stream, a common pattern is to read the output into a StringBuffer to reconstruct the original String.

 

Closing the connection

Before shutting down the connection, remember to close any open streams or readers.

reader.close ();

Invoking the close () method will clean up any nested streams or readers. This isn't clear in the documentation.

The connection can then be disconnected.

connection.disconnect ();

That's all there is to using a HTTP connection in Android.


References

The sample code for this article can be found on GitHub at:


The Javadoc for the HttpURLConnection class can be found at:

http://developer.android.com/reference/java/net/HttpURLConnection.html

This blog post gives more information as to why you should use HttpURLConnection, and a few caveats when dealing with older versions of the OS.

http://android-developers.blogspot.co.uk/2011/09/androids-http-clients.html

And the Twitter search API is documented at:

https://dev.twitter.com/docs/using-search