RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Connecting to the Web: I/O Programming in Android

Learn how to connect your Android app to the web using an HTTP connection and how to parse XML files to extract useful information.

o far all the previous articles in this Android series have been concerned with location-based services and the use of Google Maps for mapping applications. In this article, let's turn our attention to some bread-and-butter issues—like connecting your Android application to the Web to download files.

Very often, you need to connect your Android application to the outside world, such as downloading images as well as consuming web services. This article will show you how to make your Android application communicate with the outside world using an HTTP connection. You'll also learn how to parse XML files so that useful information can be extracted from XML documents.

Figure 1. The New Project: The new Android project is called HttpDownload.

Creating the Project
Using Eclipse, create a new Android project and name it HttpDownload, as shown in Figure 1.

In the HttpDownload.java file, first import the various namespaces that you will need for this project (see Listing 1).

As you'll be accessing the Internet, you'll need to add the relevant permissions to your AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    <uses-permission android:name="android.permission.INTERNET" />

    <application android:icon="@drawable/icon" 
        <activity android:name=".HttpDownload"
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
Let's define a helper function called OpenHttpConnection() that opens a connection to a HTTP server and returns an InputStream object (Listing 2).

To open a connection to a server, you first create an instance of the URL class and initialize it with the URL of the server. When the connection is established, you pass this connection to an URLConnection object. You then verify whether the protocol is indeed HTTP; if not you will throw an IOException. The URLConnection object is then cast into an HttpURLConnection object and you set the various properties of the HTTP connection. Next, you connect to the HTTP server and get a response from the server. If the response code is HTTP_OK, you then get the InputStream object from the connection so that you can begin to read incoming data from the server. The function then returns the InputStream object obtained.

In the main.xml file, insert the <ImageView> and <TextView> elements. These will allow you to visually display the downloaded images and text (Listing 3).

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date