[Android] Get HTML data from a Web page __html

Source: Internet
Author: User
Tags stringbuffer


If you want to use the Internet for your Android, you must have access to the Internet in Androidmanifest.xml (that is, add <uses-permission android:name= in it). Android.permission.INTERNET "/> Code)

As shown in the following illustration:


Then it's the code that writes the page, (that is, the Activity_main.xml file in this article)

<scrollview xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:cont" Ext= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_c Ontent "android:orientation=" vertical "android:padding=" 5DP "> <edittext androi
            D:id= "@+id/edturl" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:hint= "Enter Web site" android:inputtype= "Texturi" android:singleline= "true"/> ; Button android:id= "@+id/requesthtml" android:layout_width= "Wrap_content" android:layou t_height= "Wrap_content" android:text= "Get HTML code"/> <edittext android:id= "@+id/edtht TP "Android:layout_width=" filL_parent "android:layout_height=" wrap_content "android:hint=" Here is the HTML code for the site you entered "/> </ Linearlayout> </ScrollView>


The point is, that's the code for the Java file, but here's something to note: in Android version 2.3, you can't connect directly to the main thread, or you'll throw Android.os.NetworkOnMainThreadException error, this is because in the process of networking, the program will send requests to obtain data, but if directly in the main thread to send the request, the page will be stuck, into suspended animation state. Android later versions to prevent this, so ....


Therefore, our networking needs to operate asynchronously. Because I used to use thread before, now want to change something else, use the asynctask.


So the Java file is divided into two parts, the first part is to control the page effect and listening, the second part is used to perform asynchronous operations.


The first part of the code is as follows:

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

public class Mainactivity extends activity {

	//define Component
	private EditText edturl;
	Private EditText edthttp;
	Private Button btnrequest;

	Private String strurl;//is used to store Web site addresses

	private mytask mytask;
	@Override
	protected void onCreate (Bundle savedinstancestate) {
		super.oncreate (savedinstancestate);
		Setcontentview (r.layout.activity_main);

		Initialize component
		Edturl = (edittext) Findviewbyid (r.id.edturl);
		Edthttp = (edittext) Findviewbyid (r.id.edthttp);
		Btnrequest = (Button) Findviewbyid (r.id.requesthtml);

		Listen for button btnrequest.setonclicklistener to get HTML code
		(new View.onclicklistener () {

			@Override public
			Void OnClick (View v) {
				if (!) ( strURL = Edturl.gettext (). toString ()). Equals ("")) {
					//Instance MyTask object
					mytask = new MyTask (edthttp);
					Mytask.execute (strURL);}}}
		);
	}


The second part of the code:

Import Java.io.BufferedReader;
Import java.io.IOException;

Import Java.io.InputStreamReader;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;

Import org.apache.http.impl.client.DefaultHttpClient;

Import Com.xiaoyan.httpclienttest.r.integer;
Import Android.os.AsyncTask;

Import Android.widget.EditText; /** * For asynchronous operations to read HTML code in Web pages * * @author Jianyan */public class MyTask extends Asynctask<string, Integer, STRINGB uffer> {private EditText edthttp;//for displaying HTML code private StringBuffer sbhtml;//for storing HTML code public mytask (EditText E
		dthttp) {this.edthttp = edthttp;
	sbhtml = new StringBuffer (); /** * Doinbackground method to perform background tasks internally, do not modify UI/@Override protected StringBuffer doinbackground (String ... params) within this method
		{//Initialize HTTP client httpclient HC = new Defaulthttpclient ();

		Instantiate HttpGet object HttpGet hg = new HttpGet (params[0));
		try {//Let the HTTP client request data in the way that it has got, and assign the resulting data to the HttpResponse object	HttpResponse hr = Hc.execute (Hg);

			Read the returned data using caching BufferedReader br = new BufferedReader (new InputStreamReader (HR. getentity (). getcontent ());
			Read the page returned by the HTML code String = "";
			sbhtml = new StringBuffer ();
			while (line = Br.readline ())!= null) {sbhtml.append (line);
		return sbhtml; catch (IOException e) {edthttp.settext ("Get web page HTML code error ...)
		");
	return null; The/** * OnPostExecute method is used to update the UI after the background task finishes, displaying the results/@Override protected void OnPostExecute (StringBuffer result) {//
		Determines whether NULL, if not NULL, displays HTML code if (result!= null) {Edthttp.settext) on the page;
	} super.onpostexecute (Result);
 }
}



All the code is on the top, and then we look at the effect of the run: (Tester: ZTE U808)



The source address is as follows: [Android] get HTML data from Web pages

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.