HTTPURLConnection in Android

A Code snippet that reads a URL and print the HTML content on the screen, as raw text.
You may need to refer my earlier post to enable the necessary permissionpackage org.grassfield;

package org.grassfield;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HellodroidActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
URL url = new URL("http://www.google.com");
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = openConnection.getInputStream();
StringBuffer sb = new StringBuffer();
int c=-1;
while ((c=inputStream.read())!=-1){
sb.append((char)c);
}
inputStream.close();
TextView textView = new TextView(this);
textView.setText("Google Output ==>"+sb.toString());
setContentView(textView);
} catch (MalformedURLException e) {
e.printStackTrace();
TextView textView = new TextView(this);
textView.setText(e+"");
setContentView(textView);
} catch (IOException e) {
e.printStackTrace();
TextView textView = new TextView(this);
textView.setText(e+"");
setContentView(textView);
}
}
}

UnknownHostException while accessing Internet – Android

I am creating a new HelloWorld application for HTTP URL Connection demo. While accessing http://www.google.com, I am getting UnknownHostException

Obvious, we need to grant the permission for internet access. Hence add the android.permission.INTERNET permission in the manifest file as given below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.grassfield"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HellodroidActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>