Android Projects

Android Development Books

Sunday

HTTP Access in Android

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)

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

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 ths 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
try {
 URL url = new URL("http://www.dharmakshetri.com.np");
 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. Apache HTTP Client

Android contains the Apache HttpClient library. You can either use the DefaultHttpClient or AndroidHttpClient to setup the HTTP client.
DefaultHttpClient is the standard HttpClient and uses the SingleClientConnManager class to handle HTTP connections. SingleClientConnManager is not thread-safe, this means that access to it via several threads will create problems.
The following is an example an HTTP Get request via HttpClient.

   
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.dharmakshetri.com.np");
HttpResponse response = client.execute(request);

// Get the response
BufferedReader rd = new BufferedReader
 (new InputStreamReader(response.getEntity().getContent()));
  
String line = "";
while ((line = rd.readLine()) != null) {
 textView.append(line);
}
  

AndroidHttpClient is a special implementation of DefaultHttpClient which is pre-configured for Android.
AndroidHttpClient was introduced in Android 2.2. An instance can be received via the newInstance() method which allows to specify the user agent a parameter.
AndroidHttpClient supports SSL and has utility methods for GZIP compressed data. It registers the ThreadSafeClientConnManager which allows thread safe HTTP access via a managed connection pool.
AndroidHttpClient also applies reasonable default settings for timeouts and socket buffer sizes. It also supports HTTPS by default.

 

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

6. 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 doesn't work behind a proxy. See Bug 2764
Sources:- Vogella.com
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments

Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0