Chapter 15. Networking and Web Overview

Networking is one of the fundamental tasks of mobile development. In today’s world, the power of the smartphone lies not so much in its computational abilities as in its connections to the greater collection of servers and clients that make up the Internet. Understanding the role of networking within the Android development environment is critical. With this in mind, this chapter will cover a common form of networking: sending web data over HTTP.

Quick Example

Let us do a quick simple example of an HTTP network connection to give an idea of what we are going to cover. First, copy the code in Example 15-1 to a file called QuickHttpExample.java and run it (Example 15-2). This will produce the output as shown in Example 15-3 (we truncated the output because it is very long). What this example does is creates an HTTP connection to http://yamba.marakana.com/api/statuses/public_timeline.json (if you copy this URL into a browser you will see some very long data that is similar to the long output in the output of the program). It then proceeds to check the response status (getResponseCode()), read in the server’s output, and write that out to the system console. It terminates the connection after it is done (disconnect()).

Example 15-1. Quick example with HttpUrlConnection
package com.marakana.examples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

public class QuickHttpExample ...

Get Learning Android, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.