Support free tutorials









vogella training Training Books



Android HTTP Access - Tutorial

Lars Vogel

Version 2.3

20.04.2012

Revision History
Revision 0.1 19.07.2010 Lars
Vogel
Created
Revision 0.2 - 2.3 30.08.2010 - 20.04.2012 Lars
Vogel
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 3.7, Java 1.6 and Android 4.0 (Ice Cream Sandwich).


Table of Contents

1. Overview of HTTP access on Android
1.1. Available API's
1.2. Required permissions
2. Android StrictMode
3. HttpURLConnection
4. Check the network availability
5. Proxy
6. Support this website
6.1. Thank you
6.2. Questions and Discussion
7. Links and Literature
7.1. Source Code
7.2. Android Resources
7.3. vogella Resources

1. Overview of HTTP access on Android

1.1. Available API's

Android contains the standard Java network java.net package which can be used to access network resources. Android also contains the Apache HttpClient library.

The base class for HTTP network access in the java.net package is the HttpURLConnection class.

The preferred way of accessing the Internet according to Google is the HttpURLConnection class, as Google is focusing their efforts on improving this 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.

2. Android StrictMode

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

StrictMode allows to setup policies in your application to avoid doing incorrect things. As of Android 3.0 (Honeycomb) StrictMode is configured to crash with a NetworkOnMainThreadException exception, if network is accessed in the user interface thread.

While you should do network access in a background thread, this tutorial will avoid this to allow the user to learn network access independent from background processing.

If you are targeting Android 3.0 or higher, you can turn this check off via the following code at the beginning of your onCreate() method of your activity.

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

It is not advised to turn this of but in this book we use this setting to be able to explain network access independently from background processing.

3. HttpURLConnection

HttpURLConnection which is also available in standard Java, is a general-purpose, lightweight HTTP client suitable for most applications.

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.

// Somewhere in your code this is called
// in a thread which is not the user interface
// thread

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

6.1. Thank you

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

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

7. Links and Literature

7.1. Source Code

Source Code of Examples

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