Recipe 6.1 Connecting to Servers Using HTTP GET

Android Versions
Level 1 and above
Permissions
android.permission.INTERNET
Source Code to Download at Wrox.com
HTTP.zip

One very common way for your application to talk to the outside world is to connect to web servers. As you are probably aware, web servers use the stateless Hyper Text Transfer Protocol (HTTP) to communicate with web clients. Two main advantages of HTTP are that it is lightweight and widely deployed.

In this recipe, you learn how to connect your Android application to a web server using HTTP and download data directly from it.

Solution

To connect to a server using HTTP, you can use two methods: GET and POST. Using GET, any data (known as a query string) that you want to pass to the server is appended to the URL. The following OpenHttpGetConnection() method shows how you can open a connection to a server using the HttpClient and HttpResponse classes:

    // ---Connects using HTTP GET---
    public static InputStream OpenHttpGETConnection(String url) {
        InputStream inputStream = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
            inputStream = httpResponse.getEntity().getContent();
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return inputStream;
    }

When the connection is established, the HttpResponse object returns an InputStream object. Using the InputStream object, you can read incoming data directly ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps 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.