How to read webpage contents as a string in Android?

By | July 17, 2011

This is a simple example to read a webpage content as a string in android.
This example can also be used to get the response as a string when you make a call to a webpage.
For example a php script. You can have a http script that will call a php script and get the response.
Let the response be a Json String then you can parse the string as JSON and decode it. This code helps you to do this.
Remember that TextView can only display few html tags if displayed as HTML. However I am displaying it as simple text here.

NOTE : PLEASE ADD INTERNET PERMISSION IN THE ANDROID MANIFEST FILE.
IF YOU ARE USING ANDROID 3.0 OR ABOVE, THEN PLEASE RUN THE NETWORK OPERATION INSIDE A SEPERATE THREAD OTHERWISE THE APPLICATION WILL CRASH.

Here is the java code for doing this.

package pack.coderzheaven;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ReadWebPage extends Activity {
	private EditText url_text;
	private TextView textView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		url_text = (EditText) findViewById(R.id.address);
		textView = (TextView) findViewById(R.id.tv);
	}

	public void myButtonClickHandler(View view) {
		switch (view.getId()) {
		case R.id.ReadWebPage:
			try {
				if(!url_text.getText().toString().trim().equalsIgnoreCase("")){
					textView.setText("");
					HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(url_text.getText().toString());
					// Get the response
					ResponseHandler<String> responseHandler = new BasicResponseHandler();
			        String response_str = client.execute(request, responseHandler);
			        textView.setText(response_str);
				}else{
					Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
				}
			}
			catch (Exception e) {
				System.out.println("Some error occured.");
				textView.setText(e.getMessage());
			}
			break;
		}
	}
}

The Layout main.xml

<?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">

	<EditText android:layout_height="wrap_content"
		android:layout_width="fill_parent"
		android:id="@+id/address"
		android:hint="http://www.google.com"
		android:singleLine="true">
	</EditText>
	<Button android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Read Webpage"
		android:id="@+id/ReadWebPage"
		android:onClick="myButtonClickHandler">
	</Button>

	<ScrollView
		android:id="@+id/ScrollView01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
		<TextView
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:id="@+id/tv"
			android:scrollbars="vertical">
		</TextView>
	</ScrollView>
</LinearLayout>

Read Webpage as string Demo

Read Webpage as string Demo


Click the +1 button on top to share it with your friends.
Please leave your valuable comments.

28 thoughts on “How to read webpage contents as a string in Android?

  1. vivek

    Hi,

    When I am running your program it hangs and the emulator prompts for closing the activity.

    Do I have to make any changes in the manifest.xml file …?

    Kindly help.

    Reply
    1. James Post author

      Did you add the internet permission in the manifest file. Check the logcat for the cause of force close.

      Reply
  2. amir

    hi
    how can i using this codes?
    i should add a class with ReadWebPage name ?
    can you attach this project fiels?
    thanks

    Reply
    1. James Post author

      Sorry amir, I currently dont have this project file with me. Simply Create a project named “ReadWebPage” and it will create a java file with the same name for you and then copy the code.

      Reply
  3. Neha

    hi..! I run this code, there is no error but it does not work..when I click on button it does not show any content..can u help me?

    Reply
      1. Neha

        yes, i did it.. it throws Exception at this line
        response_str = client.execute(request, responseHandler);

        Reply
          1. Neha

            Thanks James.. Now its working properly..there was network problem..thanks again..

  4. Ravi

    Hi…!
    I m the new in android developement i want to access any web-service from my android application.can any one tell me proper steps with tutorial how to aceess webservice from android application.plz help.Hope You will think about my comment… Thanks in advaced…

    Reply
  5. Ravi

    Hi….!
    i follow your tutorial but it throws android.os.NetworkOnMainThreadException at line
    String response_str = client.execute(request, responseHandler);plz tell me hw to resolve this exception.

    Reply
  6. Ethan

    Alright; so I’ve been chasing this
    String response_str = client.execute(request, responseHandler); problem for a long time. It looks like, James, it looks like you solved it…but what did you do to solve it!? I have this tutorial copied and I have the permission in the manifest,… I don’t know what to do!

    Reply
    1. James Post author

      Compare your old not working code with this one. that’s what I can say.
      My aim is to provide working code for programmers, that’s what this site means.

      Reply
      1. Ethan

        I understand, my friend, but what I mean: this code isn’t working for me. I copied exactly what you have, added internet access to the manifest, but exceptions are being thrown for every url. It sounds like I have what Neha had, “there was network problem”, I just don’t know how to solve it, or what it was!

        Reply
  7. Gilles Fecteai

    I am getting an error on the
    import org.apache.http.client.HttpClient;
    from the eclipse compile.
    It says syntax error, simple name expected.
    I also get an error on the <span class …
    Syntax error on token <

    Do you know how to correct this?

    Reply
    1. James Post author

      Remove those span tags, that’s the problem with my syntax highlighter.

      Reply
  8. Gilles Fecteau

    I now get an error from HTTP, complaining about the been able to support GBA? Do you know how to solve this?

    Following are the log entries:

    08-22 15:11:06.326: I/APACHE HTTP (thCr=1) – NafHttpAuthStrategyDefault(4547): (thUse=1) NafHttpAuthStrategyDefault()
    08-22 15:11:06.326: I/APACHE HTTP (thCr=1) – KeeperManager(4547): (thUse=1) INITIALIZATION of shared resources
    08-22 15:11:06.336: I/APACHE HTTP (thCr=1) – AndroidContextProviderImpl(4547): (thUse=1) currentActivityThread=android.app.ActivityThread@4159dfa8
    08-22 15:11:06.346: I/APACHE HTTP (thCr=1) – NafHttpAuthStrategyDefault(4547): (thUse=1) cached value : gbaSupportIsPossible=null
    08-22 15:11:06.346: I/APACHE HTTP (thCr=1) – NafHttpAuthStrategyDefault(4547): (thUse=1) The current context is NOT a context of GBA service.
    08-22 15:11:06.346: I/APACHE HTTP (thCr=1) – GbaSupportPermissionRequestCheckerImpl(4547): (thUse=1) isCurrentProcessRequestedGba()#finished result=false
    08-22 15:11:06.356: I/APACHE HTTP (thCr=1) – GbaSupportPermissionRequestCheckerImpl(4547): (thUse=1) isCurrentProcessAllowedToUseGba()#started result=false
    08-22 15:11:06.356: I/APACHE HTTP (thCr=1) – NafHttpAuthStrategyDefault(4547): (thUse=1) The GBA permission wasn’t requested for this process.
    08-22 15:11:06.356: I/APACHE HTTP (thCr=1) – NafHttpAuthStrategyDefault(4547): (thUse=1) It is impossible to support GBA now (many possible reasons: no Android Context, current client is GBA service, etc.), then it will be just usual HTTP.
    08-22 15:11:06.356: I/APACHE HTTP (thCr=1) – NafRequestExecutorWrapperRedirectionHandler(4547): (thUse=1) It isn’t GBA flow, redirection responses are not handled.

    Reply
  9. Srinivas

    hi..! I run this code, there is no error but it does not work..when I click on button it does not show any content..can u help me?

    Reply
    1. James Post author

      Please check the internet connection on your device or emulator first. Also make sure you add the internet permission in the AndroidManifest.xml.

      Reply
  10. Emre

    Hi;

    when i use this code and start debugging i taking an error this line ;

    String response_str = client.execute(request, responseHandler);

    and application dropping catch . But e.message = null

    Phone or emulator telling me there, application is stopped. And crash..

    I need help -(

    Reply
  11. Pandora Clip Charms

    This web site definitely has all of the information and facts I needed about this subject and didn’t know who to ask.

    Reply

Leave a Reply to vivek Cancel reply

Your email address will not be published. Required fields are marked *