Connecting to an Internet Resource in Android

Before you can access Internet resources, you need to add an INTERNET uses-permission node to your application manifest, as shown in the following XML snippet:

<uses-permission android:name=”android.permission.INTERNET”/>

Opening an Internet data stream

String myFeed = getString(R.string.my_feed);
try {
 URL url = new URL(myFeed);
 // Create a new HTTP URL connection
 URLConnection connection = url.openConnection();
 HttpURLConnection httpConnection = (HttpURLConnection)connection;
 int responseCode = httpConnection.getResponseCode();
 if (responseCode == HttpURLConnection.HTTP_OK) {
 InputStream in = httpConnection.getInputStream();
 processStream(in);
 }
}
catch (MalformedURLException e) {
 Log.d(TAG, “Malformed URL Exception.”);
}
catch (IOException e) {
 Log.d(TAG, “IO Exception.”);
}

Leave a Comment