Chapter 11 explains how your application can talk to the outside world through the use of SMS messaging and emails. Another way to communicate with the outside world is through the wireless network available on your Android device. In this chapter, you find out how to use the HTTP protocol to talk to web servers so that you can download text and binary data. Also, you see how to parse XML files to extract the relevant parts of an XML document—a technique that is useful if you are accessing web services. In addition to XML web services, this chapter also covers JSON (JavaScript Object Notation), which is a lightweight alternative to XML. You make use of the classes available in the Android SDK to manipulate JSON content.
Finally, this chapter also demonstrates how to write an Android application to connect to servers using TCP sockets. Using sockets programming, you can write sophisticated, interesting networked applications.
One common way to communicate with the outside world is through HTTP. HTTP is no stranger to most people; it is the protocol that drives much of the web's success. Using the HTTP protocol, you can perform a variety of tasks, such as downloading web pages from a web server, downloading binary data, and more.
The following Try It Out creates an Android project so you can use the HTTP protocol to connect to the web to download all sorts of content.
A common task you need to perform is downloading binary data from the web. For example, you might want to download an image from a server so that you can display it in your application. The following Try It Out shows how this is done.
Besides downloading binary data, you can also download plain-text content. For example, you might want to access a web service that returns a string of random quotes. The following Try It Out shows how you can download a string from a web service in your application.
So far, this chapter has showed you how to download images and text from the web. The previous section demonstrated how to download some plain text from a server. Very often, you need to download XML files and parse the contents (a good example of this is consuming web services). Therefore, in this section you learn how to connect to a web service using the HTTP GET method. After the web service returns a result in XML, you extract the relevant parts and display its content using the Toast class.
In this example, you use the web method from http://services.aonaware.com/DictService/DictService.asmx?op=Define. This web method is from a dictionary web service that returns the definition of a given word.
The web method takes a request in the following format:
GET /DictService/DictService.asmx/Define?word=string HTTP/1.1
Host: services.aonaware.com
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
It returns a response in the following format:
<?xml version="1.0" encoding="utf-8"?>
<WordDefinition xmlns="http://services.aonaware.com/webservices/">
<Word>string</Word>
<Definitions>
<Definition>
<Word>string</Word>
<Dictionary>
<Id>string</Id>
<Name>string</Name>
</Dictionary>
<WordDefinition>string</WordDefinition>
</Definition>
<Definition>
<Word>string</Word>
<Dictionary>
<Id>string</Id>
<Name>string</Name>
</Dictionary>
<WordDefinition>string</WordDefinition>
</Definition>
</Definitions>
</WordDefinition>
Hence, to obtain the definition of a word, you need to establish an HTTP connection to the web method and then parse the XML result that is returned. The following Try It Out shows you how.
In the previous section, you learned how to consume XML web services by using HTTP to connect to the web server and then obtain the results in XML. You also learned how to use DOM to parse the result of the XML document. However, manipulating XML documents is a computationally expensive operation for mobile devices, for the following reasons:
DocumentBuilderFactory, you must use DOM to traverse the tree in order to locate the information you want. In addition, DOM itself has to build the entire document in memory as a tree structure before you can traverse it. This is both memory and CPU intensive.A much more efficient way to represent information exists in the form of JSON (JavaScript Object Notation). JSON is a lightweight data-interchange format that is easy for humans to read and write. It is also easy for machines to parse and generate. The following lines of code show what a JSON message looks like:
[
{
"appeId":"1",
"survId":"1",
"location":"",
"surveyDate":"2008-03 14",
"surveyTime":"12:19:47",
"inputUserId":"1",
"inputTime":"2008-03-14 12:21:51",
"modifyTime":"0000-00-00 00:00:00"
},
{
"appeId":"2",
"survId":"32",
"location":"",
"surveyDate":"2008-03-14",
"surveyTime":"22:43:09",
"inputUserId":"32",
"inputTime":"2008-03-14 22:43:37",
"modifyTime":"0000-00-00 00:00:00"
},
{
"appeId":"3",
"survId":"32",
"location":"",
"surveyDate":"2008-03-15",
"surveyTime":"07:59:33",
"inputUserId":"32",
"inputTime":"2008-03-15 08:00:44",
"modifyTime":"0000-00-00 00:00:00"
},
{
"appeId":"4",
"survId":"1",
"location":"",
"surveyDate":"2008-03-15",
"surveyTime":"10:45:42",
"inputUserId":"1",
"inputTime":"2008-03-15 10:46:04",
"modifyTime":"0000-00-00 00:00:00"
},
{
"appeId":"5",
"survId":"32",
"location":"",
"surveyDate":"2008-03-16",
"surveyTime":"08:04:49",
"inputUserId":"32",
"inputTime":"2008-03-16 08:05:26",
"modifyTime":"0000-00-00 00:00:00"
},
{
"appeId":"6",
"survId":"32",
"location":"",
"surveyDate":"2008-03-20",
"surveyTime":"20:19:01",
"inputUserId":"32",
"inputTime":"2008-03-20 20:19:32",
"modifyTime":"0000-00-00 00:00:00"
}
]
The preceding block of lines represents a set of data taken for a survey. Note that the information is represented as a collection of key/value pairs, and that each key/value pair is grouped into an ordered list of objects. Unlike XML, there are no lengthy tag names. Instead, there are only brackets and braces.
The following Try It Out demonstrates how to process JSON messages easily using the JSONArray and JSONObject classes available in the Android SDK.
In this chapter, you learned how your application can connect with the outside world through the use of the HTTP protocol. Using the HTTP protocol, you can download various types of data from web servers. One good application of this is to talk to web services, whereby you need to parse XML files. In addition to XML web services, you also saw how to consume JSON services, which are more lightweight than XML web services. Finally, you saw an alternative to HTTP: using sockets for communication. Sockets enable your application to remain connected to a server so that it can receive data as it becomes available. An important lesson in this chapter is that all synchronous operations must be encapsulated using the AsyncTask class. Otherwise, your application does not work on devices running Honeycomb or later.
AndroidManifest.xml file for an HTTP connection.You can find answers to the exercises in the appendix.
| Topic | Key Concepts |
| Establishing an HTTP connection | Use the HttpURLConnection class. |
| Accessing XML web services | Use the Document, DocumentBuilderFactory, and DocumentBuilder classes to parse the XML result returned by the web service. |
| Dealing with JSON messages | Use the JSONArray and JSONObject classes. |
| Sockets programming | Use the Socket class to establish a TCP connection. Use the InputStream and OutputStream objects for receiving and sending data, respectively. |
The three methods in an AsyncTask class |
The three methods are doInBackground(), onProgressUpdate(), and onPostExecute(). |