文章标题
2017-03-27 20:41
190 查看
网络源码查看器
实现步骤
//这是工具类 public class Utils { public static String getTextFromStream(InputStream is) { byte[] b = new byte[1024]; int len = 0; //创建字节数组输出流,读取输入流的文本数据,挺尸把数据写入到输出流 ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { //is.read(b)以什么单位进行读取 while ((len = is.read(b)) != -1) { bos.write(b,0,len); } //把字节数组转换成字节数组 String text = new String(bos.toByteArray()); return text; } catch (Exception e) { e.printStackTrace(); } return null; } }
实现步骤
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { tv.setText((String)msg.obj); } }; public void click(View v){ new Thread(){ String text1; @Override public void run() { try { String path = "https://www.baidu.com"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(3000); if (conn.getResponseCode()==200){ InputStream is = conn.getInputStream(); text1 = Utils.getTextFromStream(is); Message msg = Message.obtain(); msg.obj = text1; handler.sendMessage(msg); }else{ Toast.makeText(MainActivity.this,"链接失败",Toast.LENGTH_LONG).show(); } } catch (Excep 8241 tion e) { e.printStackTrace(); } }; }.start(); }