The previous article mainly introduces the download and display of the picture file, this article mainly introduces how to obtain the source code of the webpage according to the address of the webpage
In fact, the site source code is easier to download and display than the picture, only need to modify the previous code slightly
public class Otheractivity extends Activity {private TextView tv;private static final int load_success = 1;private static Final int load_error = -1;private Handler Handler = new Handler () {public void Handlemessage (Message msg) {switch (Msg.wha T) {case LOAD_SUCCESS:tv.setText (String) msg.obj); Break;case LOAD_ERROR:Toast.makeText (Getapplicationcontext (), " Load failed ", 0). Show (); break;}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); TV = (TextView) Findviewbyid (r.id.tv);} Click event for button public void Show (view view) {New Thread (new Runnable () {public void run () {gethttp ()}}). Start ();} The main method of downloading a picture private void Gethttp () {URL url = null;inputstream is = null; Bytearrayoutputstream Bytearrayoutputstream = null;try {//URL address URL of the build picture = new URL ("http://www.baidu.com");// Open connection HttpURLConnection conn = (httpurlconnection) url.openconnection ();//Set time-out, 5000 milliseconds, 5 seconds conn.setconnecttimeout ( 5000)///set to get the picture in the way getconn.setreqUestmethod ("GET"), if (conn.getresponsecode () = =) {is = Conn.getinputstream (); bytearrayoutputstream = new Bytearrayoutputstream (); int len = 0;byte[] buffer = new Byte[1024];while (len = is.read (buffer))! =-1) {bytearrayoutputs Tream.write (buffer, 0, Len);} Bytearrayoutputstream.flush (); byte[] arr = Bytearrayoutputstream.tobytearray (); Message msg = Handler.obtainmessage (); msg.what = Load_success;msg.obj = new String (arr); Handler.sendmessage (msg);}} catch (Exception e) {handler.sendemptymessage (load_error); E.printstacktrace ();} finally {try {if (is! = null) {Is.close ( );} if (bytearrayoutputstream! = null) {Bytearrayoutputstream.close ();}} catch (Exception e) {handler.sendemptymessage (load_error); E.printstacktrace ();}}}
Layout file
<linearlayout 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 " android:orientation= "vertical" > <button android:layout_width= "Match_parent" android: layout_height= "Wrap_content" android:layout_gravity= "bottom" android:onclick= "show" android:text= "Show"/> <textview android:id= "@+id/tv" android:layout_width= "Match_parent" android: layout_height= "Match_parent"/></linearlayout>
Permissions
<uses-permission android:name= "Android.permission.INTERNET"/>