Tutorial details

Android HTTP Access  | App Code for Sale | Preview

Android HTTP Access | Android Tutorial

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

Overview PAGE TOP

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

Reference

http://www.vogella.de under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany (CC BY-NC-SA 3.0) licence.

Overview of HTTP access on Android PAGE TOP

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.

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

Android StrictMode PAGE TOP

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 tutorial we use this setting to be able to explain network access independently from background processing.

HttpURLConnection PAGE TOP

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.

Check the network availability PAGE TOP

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

Proxy PAGE TOP

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

proxy.jpg

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

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.