Mainly used in the Bytearrayoutputstream class. Instead of specifying the path to the output stream, the class outputs the data directly to the memory buffer.
Use the Tobytearray method to get the memory buffer data.
1 PackageCom.example.day10_03htmlsourceViewer;2 3 ImportJava.io.ByteArrayOutputStream;4 ImportJava.io.InputStream;5 Importjava.net.HttpURLConnection;6 ImportJava.net.URL;7 Importandroid.app.Activity;8 ImportAndroid.os.Bundle;9 ImportAndroid.os.Handler;Ten ImportAndroid.os.Message; One ImportAndroid.view.View; A ImportAndroid.widget.TextView; - ImportAndroid.widget.Toast; - the Public classMainactivityextendsActivity { - @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); - } + A Final Static intMSG_DOWNLOAD_OK =1; at Final Static intMsg_download_error =2; - -Handler Handler =NewHandler () { - @Override - Public voidhandlemessage (Message msg) { - Super. Handlemessage (msg); in - Switch(msg.what) { to CaseMSG_DOWNLOAD_OK: +TextView tv_html=(TextView) Findviewbyid (r.id.tv_html); - Tv_html.settext ((String) msg.obj); the Break; * CaseMsg_download_error: $Toast.maketext (mainactivity. This, "Download source failed", 1). Show ();Panax Notoginseng Break; - default: the Break; + } A } the }; + Public voidgethtml (View v) { -Thread thread =NewThread () { $ Public voidrun () { $String Path = "Http://192.168.3.30:8080/index2.html"; - Try { -URL url =NewURL (path); theHttpURLConnection conn =(HttpURLConnection) url.openconnection (); - WuyiConn.setconnecttimeout (5000); theConn.setreadtimeout (5000); -Conn.setrequestmethod ("GET"); Wu Conn.connect (); - About if(Conn.getresponsecode () ==200) $ { -InputStream is =Conn.getinputstream (); - -Bytearrayoutputstream BAOs =NewBytearrayoutputstream (); A byte[] B =New byte[1024]; + intLen = 0; the while((Len=is.read (b))!=-1) - { $Baos.write (b, 0, Len); the } the is.close (); the Baos.close (); theString Htmlsource =NewString (Baos.tobytearray (), "GBK") ; -Message msg=handler.obtainmessage (); inmsg.what=Msg_download_ok; themsg.obj=Htmlsource; the handler.sendmessage (msg); About } the Else { theMessage msg=handler.obtainmessage (); themsg.what=Msg_download_error; + handler.sendmessage (msg); - } the}Catch(Exception e) {Bayi e.printstacktrace (); the } the } - ; - }; the Thread.Start (); the } the}
Activity_main.xml and Androidmanifest.xml are the same as the 010_02 with cached picture viewers.
:
010_03html Source Viewer