The previous article mainly introduced the download and display of image files. This article mainly describes how to obtain the source code of a webpage based on the webpage address.
In fact, obtaining the website source code is simpler than downloading and displaying images. You only need to slightly modify the previous code.
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. what) {case LOAD_SUCCESS: TV. setText (String) msg. obj); break; case LOAD_ERROR: Toast. makeText (getApplicationContext (), "loading failed", 0 ). show (); break ;};};@ Overrideprotec Ted void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); TV = (TextView) findViewById (R. id. TV) ;}// Button click event public void show (View view) {new Thread (new Runnable () {public void run () {getHttp ();}}). start () ;}// the main method for downloading images. private void getHttp () {URL url = null; InputStream is = null; ByteArrayOutputStream byteArrayOutputStream = null; try {/ /Construct the image url = new URL ("http://www.baidu.com"); // enable the connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set the timeout time, 5000 milliseconds, that is, 5 seconds conn. setConnectTimeout (5000); // you can call GETconn to retrieve an image. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {is = conn. getInputStream (); byteArrayOutputStream = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buf Fer ))! =-1) {byteArrayOutputStream. 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
Permission