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.

 

27 Comments

  1. vivek October 20, 2011 at 11:58 am

    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.

     
    • James October 20, 2011 at 10:02 pm

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

       
  2. amir January 4, 2012 at 12:25 am

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

     
    • James January 4, 2012 at 12:33 am

      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.

       
  3. Neha January 31, 2012 at 5:30 pm

    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?

     
    • James January 31, 2012 at 8:12 pm

      Did you add the internet permission in the manifest file.

       
      • Neha February 1, 2012 at 3:10 pm

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

         
        • James February 1, 2012 at 8:38 pm

          what is the exception? please paste it here.

           
          • Neha February 2, 2012 at 5:51 pm

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

             
  4. Ravi February 20, 2012 at 4:41 pm

    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…

     
  5. Ravi February 21, 2012 at 1:51 pm

    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.

     
    • James February 21, 2012 at 7:19 pm

      Did you add the internet permission in the manifest?

       
  6. Ethan February 28, 2012 at 11:03 pm

    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!

     
    • James February 28, 2012 at 11:15 pm

      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.

       
  7. Gilles Fecteai August 20, 2012 at 8:10 pm

    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?

     
    • James August 21, 2012 at 10:25 am

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

       
  8. Gilles Fecteau August 20, 2012 at 8:11 pm

    Correcting the typo in my name on the previous post.

     
  9. Gilles Fecteau August 22, 2012 at 7:24 pm

    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.

     
  10. shinto joseph October 14, 2013 at 5:41 am

    does it work for localhost

     
    • James October 14, 2013 at 5:05 pm

      yes. but change the host url t0 10.0.0.2

       
  11. Srinivas September 16, 2014 at 10:39 am

    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?

     
    • James October 9, 2014 at 10:41 am

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

       
  12. Emre January 5, 2015 at 12:02 pm

    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 -(

     
    • James June 26, 2015 at 9:20 am

      please do it inside a thread.

       

Leave a Reply

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

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.