Statement: This is a study summary, we have the need to see, do not need to also see. Okay, just on the code.
First, there is a tool class to fetch data from the stream:
import java.io.bytearrayoutputstream;import java.io.inputstream;/** * @author wesley * @version * @date 2015 January 30 PM 2:12:28 * */public class StreamUtils {/** * reading data from a stream * @param in * @ return * @throws exception */public static byte[] readstream ( Inputstream in) throws exception{ bytearrayoutputstream bstream = new bytearrayoutputstream (); int len = 0; byte[] data = new byte[1024]; while ((len = In.read (data))!=-1) { bstream.write (Data, 0, len); } in.close (); return Bstream.tobytearray (); }}
Get the service layer for network resource data: (Here we assume the source of the Web page)
import java.io.inputstream;import java.net.httpurlconnection;import java.net.url;import com.example.utils.streamutils;/** * @author wesley * @version * @date 2015 January 30 PM 2:15:12 * */public class pageservice { public static string getpage (String path) throws Exception{ url url = new url (PATH); HttpURLConnection connection = (httpurlconnection) Url.openconnection (); connection.setconnecttimeout (; ) connection.setrequestmethod ("GET"); if (Connection.getresponsecode () ==200) { &nBsp;inputstream in = connection.getinputstream (); byte[] data = streamutils.readstream (in); return New string (data, "UTF-8"); } return null; }}
The previous blog has written that it is no longer possible to access the network in the main thread, so I use the handler thread the last time.
Button Listener Event: (code is also a well-defined global variable)
private final class buttonlistener implements onclicklistener{ @Override public void onclick (view v) { // TODO Auto-generated method stub final string path = pagepath.gettext (). toString (); final handler handler = new handler () { public void handlemessage (Message msg) { switch (msg.what) { case 0: codeview.settext (code); break; } } }; new thread () { public void run () { try { code = pageservice.getpage (PATH); } catch (exception e) { // TODO Auto-generated catch block e.printstacktrace (); } &nBsp;handler.sendemptymessage (0); } }.start (); }}
Permissions:
<uses-permission android:name= "Android.permission.INTERNET"/>
Android series four (get resources on the network)