Published: 05 Oct 2011
By: Dino Esposito

Let's see what it takes in Android to place calls over HTTP to a remote endpoint.

Contents [hide]

The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • Introduction

    Internet connectivity is not mandatory for just every mobile application, but a significant share of mobile applications are just built around HTTP capabilities and some Web server. Personally, I see the combination of mobile and Web sites as the most compelling development of the next few months.

    Sounds like an old idea? Sounds like I'm just late to the party? Well, consider that too many people (not to mention gurus and pundits :-)) are still convinced that a mobile site is just the desktop site with a different master page or simply a new iPhone-like CSS style sheet. The vast majorities of ASP.NET developers are satisfied with the IsMobile property of the ASP.NET Browser object and believe that any portable device is just a mobile device.

    Don't be surprised by the potential that the integration of mobile solutions (mobile sites and/or native applications) with a classic Web server can unleash. So for now let's see what it takes in Android to place calls over HTTP to a remote endpoint.

    Checking the Network State

    In a Web application you probably never need to check if the underlying network is available. If yours is a classic Web application, the browser displays the HTML page, the user clicks to follow a link, the browser hangs for a while and then displays an apologetic error page. If yours is an Ajax application, then when the user clicks the button to start the operation, your script code fails, intercept the exception and degrades gracefully with an action that is well integrated with the user interface.

    When you connect to a site using a laptop, you're likely leveraging a wifi or cable connection. Nothing is certain in this imperfect world, but a wifi connection (over a good network infrastructure) consumed through a laptop is not as likely to go down as it is a wifi connection consumed through a mobile phone. Why? Well, because the user of a mobile phone is likely on the go and the wireless connection can simply go out of range in a matter of minutes.

    What does it mean? In a mobile application, checking the state and the type of the network before embarking in Internet operations is crucial. If the operation is critical too, you might want also to apply different algorithms, or take different countermeasures, if the user is connected via a wifi network or a mobile network. Large uploads of documents - for example a synchronization procedure between client and server - should be planned carefully: the more it takes to upload, the higher the risks for the network to go down. Handling these nasty situations is up to you.

    Unless you're coding your own synchronization framework, however, checking the network state and type is not a big deal. It only requires that you get familiar with a couple of Android API functions. Let's find out more.

    First and foremost, for an Android-based mobile device programmatic access to the Internet is subject to permissions. In particular, you need to declare in the application manifest file that the application is going to check the network state and access the Internet. Why is it also required to declare the intention of simply checking the network state? In Android, you check the network state via the ConnectivityManager class - a system class that doesn't simply exist to answer your inquiries but it also monitors all possible connections (including wifi, UMTS, GPRS) and their changes. The class may broadcast activities and intents about network changes and has the ability to try to fail over to another type of network when some type connectivity is lost. In a nutshell, the ConnectivityManager class allows applications to access any available information about any available networks. As you can see, it is a rather critical class and Android designers reckoned you must require the permission to use it so that end users can be notified of that when they install your application. Here's the code you need to enter in the application's manifest file:

    The ConnectivityManager class offers two key methods - getNetworkInfo and getActiveNetworkInfo. Both methods return a NetworkInfo object through which you can examine the state of the network and make your further decisions. The former method checks just the specified type of network (wifi, GPRS, and the like); the latter, instead, checks the currently active network, if any. Here's how to use the class:

    The getSystemService method is defined on the Context class and is then available on any Activity class - the Activity class in fact inherits from Context. In Android, a context is used in several places and for several reasons; the most common scenario, however, is to load and access resources. It is not uncommon that you find yourself in the need of an activity context object while you're trying to split your code into distinct classes. For example, suppose you want to move the code that checks the network state to a distinct class to make the code a lot more reusable in the project. You may create a class like the HttpHelper class below:

    Unfortunately, this code won't even compile: you need a Context object to reference getSystemService. The context object must be passed into the class. You can do that through the class constructor or via a static method that you invoke at the startup of the application.

    The Initialize method will basically cache the context reference and shares that with the methods of your class.

    Downloading Data from a Web Server

    Now that we have available a tool to detect whether we can connect to resources available over the Internet, it's time to look into basic HTTP commands such as GET and POST. In Android, downloading data via HTTP is quite simple; processing downloaded data into usable data objects is significantly more bothersome than in .NET. The Android API lacks some of the facilities that make downloading data from the Web a piece of cake in Silverlight or Windows Phone 7. Here's the code required to arrange a call.

    As a first step, you get a new instance of the DefaultHttpClient class. This class governs the execution of the request, grabs request headers and body and downloads a response packet. The request itself is packaged in an ad hoc class that depends on the HTTP verb to use. So you have HttpGet for a HTTP GET command and HttpPost for a HTTP POST command. You also have available other analogous classes such as HttpDelete, HttpPut and HttpHead. On the request object you can set headers and the URL to call. To execute a request you call the execute method on the DefaultHttpClient object. This method works synchronously and returns a HttpResponse object. The response object always wraps a final response with a valid HTTP status code.

    For asynchronous operations you use a different API centered on the HttpConnection class. As you can see, it allows you to create a self-contained function that embeds details of the call and response handler.

    You create a handler object and pass it to the HttpConnection class. Based on the URL, the connection class operates and then invokes the handler for producing actual results.

    In the asynchronous scenario the Message object represents the response you've got. In synchronous operations, you need to write some ad hoc code to extract usable data from the response stream. In .NET, this same work takes three or four lines of crystal clear code. In Android, it takes a bit more. First, you access the content being returned as a stream:

    Next, you have to read the content of the stream. For this purpose, you get a reader. If you want to read piecemeal, you can stick to a basic reader. If you want to read lines of text, you may use the BufferedReader class.

    If the response is on a single line - a fairly common scenario - then the BufferedReader class helps with its readLine method. If you want to read the entire content regardless of the number of lines, you have to implement a loop yourself.

    Posting Data to a Web Server

    To post data to a Web server, you change the class you use for the request: instead of HttpGet, you use HttpPost. Beyond that, placing a POST call differs from a GET call for the extra work it takes to write name/value pairs in the body of the request packet. Here's the code:

    You first create a name/value pairs to populate the body of the POST request and then attach the dictionary to the request.

    Summary

    Overall, making HTTP calls from within Android applications is straightforward as it may be in .NET and Windows Phone but it is much less complicated than other aspects of Android programming - e.g., dialog boxes. The API can be synchronous or asynchronous. Finally, when it comes to Internet operations from within a mobile device, checking the state and types of the network before you go is a true necessity. Otherwise, you risk to get run time exceptions and unexpected errors in your application.

    The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Dino Esposito

    Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...

    This author has published 53 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Developing a Hello World Java Application and Deploying it in Windows Azure - Part I
    This article demonstrates how to install Windows Azure Plugin for Eclipse, create a Hello World appl...
    Android for .NET Developers - Building a Twitter Client
    In this article, I'll discuss the features and capabilities required by an Android application to ta...
    Ref and Out (The Inside Story)
    Knowing the power of ref and out, a developer will certainly make full use of this feature of parame...
    Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
    In this article we will see the steps involved in deploying the WAR created in the first part of thi...
    Android for .NET Developers - Using Web Views
    In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...

    You might also be interested in the following related blog posts


    Generate stunning ASP.NET/AJAX applications with Web Site Factory read more
    WcfTestClient with Windows Azure read more
    TIP: How To Generate a Fully Qualified URL in ASP.NET (E.g., http://www.yourserver.com/folder/file.aspx) read more
    IIS Media Services 3.0 read more
    RELEASED ASP.NET MVC 2 Preview 2 read more
    Stimulsoft Reports. New versions of reporting tools for .NET, Web, and WPF read more
    Quick Reference Guide for Telerik Support read more
    Western European ReMix Tour 2009 read more
    MvcContrib version control has moved to GitHub read more
    ASP.NET disk-based caching read more
    Top
     
     
     

    Please login to rate or to leave a comment.

    Free Agile Project Management Tool from Telerik
    TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.