NOW Hiring

Quick links

Share

Performing HTTP operations with Android. This article describes how to access web resources via HTTP in Android. It is based on Eclipse 4.4, Java 1.6 and Android 5.0 (Lollipop).

1. Overview of network access on Android

1.1. Accessing the network in Android

Android contains the standard Java network java.net package which can be used to access network resources. The base class for HTTP network access in the java.net package is the HttpURLConnection class.

Older Android versions also contains the Apache HttpClient library. But Google recommends not to use this library, as Android version of HttpURLConnection is highly efficient.

Performing network operations with standard Java API can be cumbersome. You have to open and close a connections, enable caches and ensure to perform the network operation in a background thread.

To simplify these operations several popular Open Source libraries are available. The most popular ones are the following:

  • OkHttp for efficient HTTP access

  • Retrofit for REST based clients

  • Glide for image processing

1.2. Permission to access the network

To access the Internet your application requires the android.permission.INTERNET permission. On modern Android API versions, this permission is automatically granted to your application.

1.3. Check the network availability

The network on an Android device is not always available. To check the network state your application requires the android.permission.ACCESS_NETWORK_STATE permission. You can check the network is currently available via the following code.

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

This requires the ACCESS_NETWORK_STATE permission.

1.4. Good practices for network access under Android

Within an Android application you should avoid performing long running operations on the user interface thread. This includes file and network access.

As of Android 3.0 (Honeycomb) the system is configured to crash with a NetworkOnMainThreadException exception, if network is accessed in the user interface thread.

A typical setup for performing network access in a productive Android application is using a service. While it is possible to do network access from an activity or a fragment, using a service typical leads to a better overall design because you code in the activity becomes simpler.

For testing you can allow network access in the main thread via the following snippet at the beginning of your onCreate() method of your activity.

StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Unresolved directive in 001_article.adoc - include::../JavaNetworking/010_overview.adoc[] == Web Sockets

Web Sockets are a standard based on HTTP for asynchronous message-based communication between a client and a server. To start a web socket communication, you create a HTTP GET request with a special HTTP headers. If the server accepts this request, the client and the server can send each other messages.

Messages can be text or binary data and should be relatively small, as the web socket protocol is intended to be used with small payloads in the data.

It is good practice to use JSON as data format for the messages.

You find a Java library for both the server and the client under http://java-websocket.org/.

2. About this website

3.2. vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.