Support free tutorials









vogella training Training Books



Android Networking - Tutorial

Lars Vogel

Version 2.4

10.11.2014

Revision History
Revision 0.1 - 2.4 19.07.2010 - 20.04.2012 Lars
Vogel
Created, bug fixes and enhancements

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).


Table of Contents

1. Overview of HTTP access on Android
1.1. Available official API's
1.2. Required permissions
1.3. Open source libraries
2. Good practices for network access under Android
3. Java and HTTP access
4. Check the network availability
5. Proxy
6. Web Sockets
7. Support this website
7.1. Thank you
7.2. Questions and Discussion
8. Links and Literature
8.1. Source Code
8.2. Android Resources
8.3. vogella Resources

1. Overview of HTTP access on Android

1.1. Available official API's

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.

Tip

Android also contains the Apache HttpClient library but it is not recommended anymore to use it, as Google is focusing their efforts on improving the HttpURLConnection implementation.

1.2. Required permissions

To access the Internet your application requires the android.permission.INTERNET permission.

To check the network state your application requires the android.permission.ACCESS_NETWORK_STATE permission.

1.3. Open source libraries

Performing network operations on Android 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:

  • Volley

  • OkHttp

2. 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.

Tip

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); 

3. Java and HTTP access

Java provides a general-purpose, lightweight HTTP client API to access resources via the HTTP or HTTPS protocol. The main classes to access the Internet are the java.net.URL class and the java.net.HttpURLConnection class.

The URL class can be used to define a pointer to a web resource while the HttpURLConnection class can be used to access a web resource.

HttpURLConnection allows you to create an InputStream.

Once you have accessed an InputStream you can read it similarly to an InputStream from a local file.

In the latest version HttpURLConnection supports the transparent response compression (via the header Accept-Encoding: gzip, Server Name Indication (extension of SSL and TLS) and a response cache.

The API is relatively straight forward. For example to retrieve the webpage www.vogella.com you can use the following example.

try {
  URL url = new URL("http://www.vogella.com");
  HttpURLConnection con = (HttpURLConnection) url
    .openConnection();
  readStream(con.getInputStream());
  } catch (Exception e) {
  e.printStackTrace();
}



private void readStream(InputStream in) {
  BufferedReader reader = null;
  try {
    reader = new BufferedReader(new InputStreamReader(in));
    String line = "";
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if (reader != null) {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
        }
    }
  }
} 

The Javadoc of HttpURLConnection suggest to not reuse on HttpURLConnection. If you use it this way, HttpURLConnection has no threading issues, as it will not be shared between different Threads.

4. Check the network availability

Obviously the network on an Android device is not always available. 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.

5. Proxy

This chapter is only relevant for you if you are testing with the Android simulator behind a proxy. You can set the proxy via the Settings class. For example you could add the following line to your onCreate method in your activity.

Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080"); 

To change the proxy settings you have to have the android.permission.WRITE_SETTINGS permission in your AndroidManifest.xml file.

Tip

It seems that DNS resolving does not work behind a proxy. See Bug 2764

6. 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/.

7. Support this website

This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this tutorial is distributed under the Eclipse Public License. See the vogella License page for details on the terms of reuse.

Writing and updating these tutorials is a lot of work. If this free community service was helpful, you can support the cause by giving a tip as well as reporting typos and factual errors.

7.1. Thank you

Please consider a contribution if this article helped you. It will help to maintain our content and our Open Source activities.

7.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

8. Links and Literature

8.1. Source Code

Source Code of Examples

8.3. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java, compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put all your files in a distributed version control system