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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s