Vous êtes sur la page 1sur 4

Android Networking - Tutorial

http://www.vogella.de/articles/AndroidNetworking/article.html

Android Networking - Tutorial


Lars Vogel
Version 1.2 Copyright 2009 - 2011 Lars Vogel 09.09.2011
Revision History
Revision 0.1 Created Revision 0.2 - 1.1 bug fixes and enhancements 30.08.2010 - 09.09.2011 Lars Vogel 19.07.2010 Lars Vogel

Networking with Android This article describes how to access web resources in Android. It is based on Eclipse 3.7, Java 1.6 and Android 2.3.3 (Gingerbread). Table of Contents 1. Android Networking 1.1. Networking 1.2. Android Basics 2. URL example 3. Check the network availability 4. Proxy 5. Thank you 6. Questions and Discussion 7. Links and Literature 7.1. Source Code 7.2. Android Resources 7.3. vogella Resources

1. Android Networking
1.1. Networking
Android contains the Apache HttpClient library and this library is the preferred way of performing network operations in Android. Android also allows to access the network via the standard Java Networking API (java.net package). Even if you use the java.net package Android will internally use the Apache library. For XML parsing Android provides the class "XmlPullParser" which is an Android specific XML parser. The standard SAX and DOM XML parsers are also available on Android. The Javadoc of "XmlPullParser" gives a nice example how you can use this library. As of Android 2.2 you can also use the AndroidHttpClient. An instance can be received via newInstance() which allows to specify the user agent. AndroidHttpClient supports SSL and has utility methods for GZIP compressed data. To access the internet your application requires the "android.permission.INTERNET" permission.

1.2. Android Basics


The following assumes that you have already basic knowledge in Android development .

2. URL example
Create the project "de.vogella.android.network.html" with the activity "ReadWebpage". Change the layout "main.xml" to the following.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout> <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/address"></EditText> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read Webpage" android:id="@+id/ReadWebPage" android:onClick="myClickHandler"></Button> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/pagetext" android:scrollbars="vertical"></TextView> </LinearLayout>

Add the permission "android.permission.INTERNET" to "AndroidManifest.xml" to allow your application to access the internet.

1 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

http://www.vogella.de/articles/AndroidNetworking/article.html

Create the following code to read a webpage and show the HTML code in the TextView. This example also demonstrate the usage of Android preferences to store user data. The URL which the user has typed is stored in the preferences in the method onPause(). This method is called whenever the Activity is send into the background.
package de.vogella.android.network.html; import java.io.BufferedReader; import java.io.InputStreamReader; import import import import import import import import import import import org.apache.http.HttpResponse; org.apache.http.client.HttpClient; org.apache.http.client.methods.HttpGet; org.apache.http.impl.client.DefaultHttpClient; android.app.Activity; android.content.SharedPreferences; android.content.SharedPreferences.Editor; android.os.Bundle; android.view.View; android.widget.EditText; android.widget.TextView;

public class ReadWebpage extends Activity { private static final String PREFERENCES = "PREFERENCES"; private static final String URL = "url"; private String lastUrl; private EditText urlText; private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); urlText = (EditText) findViewById(R.id.address); textView = (TextView) findViewById(R.id.pagetext); loadPreferences(); urlText.setText(lastUrl); } /** * Demonstrates loading of preferences The last value in the URL string will * be loaded */ private void loadPreferences() { SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); // Set this to the Google Homepage lastUrl = preferences.getString(URL, "http://209.85.229.147"); } @Override protected void onPause() { super.onPause(); SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); Editor preferenceEditor = preferences.edit(); preferenceEditor.putString(URL, urlText.getText().toString()); // You have to commit otherwise the changes will not be remembered preferenceEditor.commit(); } public void myClickHandler(View view) { switch (view.getId()) { case R.id.ReadWebPage: try { textView.setText(""); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlText.getText().toString()); 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); } } catch (Exception e) { System.out.println("Nay, did not work"); textView.setText(e.getMessage()); } break; } } }

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

2 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

http://www.vogella.de/articles/AndroidNetworking/article.html

} return false; }

Android Apps Dev Group Discuss Android Apps creation, development, and programming. Wireless.ittoolbox.com Gps Software Free Technical Search Engine Search Thousands of Catalogs Today www.globalspec.com Beyondsoft A leading IT services company with Global Delivery Centers. www.beyondsoft.com

4. Proxy
This chapter is only relevant for you if you are testing with the Android similator behind a proxy. In class you are behind a proxy during your testing you can set the proxy via the class "Settings". 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 permission "android.permission.WRITE_SETTINGS" in "AndroidManifest.xml".

It seems that DNS resolving doesn't work behind a proxy. See Bug 2764

5. Thank you
Please help me to support this article:

6. Questions and Discussion


Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.

7. Links and Literature


7.1. Source Code
Source Code of Examples

3 de 4

05/09/2011 09:06 p.m.

Android Networking - Tutorial

http://www.vogella.de/articles/AndroidNetworking/article.html

7.2. Android Resources


Introduction to Android Development Android Location API and Google Maps Android Homepage Crest Framework to access rest services, works also on Android

7.3. vogella Resources


Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system

4 de 4

05/09/2011 09:06 p.m.

Vous aimerez peut-être aussi