android socket之查看网页源码

来源:互联网 发布:拆棋软件 编辑:程序博客网 时间:2024/06/05 06:37
   小编最近刚刚在学习android,自然要在网上当写视频下来照猫画虎的练习代码。但在练习网络通信这章视频时遇到一一些问题。特此整理一下,给遇到相同问题的同学一个参考。
   代码是表示网路通信中的网络源码查看器,即点击按钮显示网页源码,代码如下:
   [code=java]
       String path = "http://192.168.0.133:8080/Brower/index.html";
          try {
               URL url = new URL(path);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               InputStream inStream = conn.getInputStream();
               ByteArrayOutputStream outStream = new ByteArrayOutputStream();
               byte[] buffer = new byte[1024];
           int len = 0;
          while( (len = inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);}                        
          html = new String(outStream.toByteArray(), "UTF-8");
              codeView.setText(html);
   [/code]
代码会报android.os.NetworkOnMainThreadException 的异常
是因为不可以在主线程中进行耗时操作,要另外开启一个线程。
OK当开启一个线程后代码执行到codeView.setText(html);时又报错,这是因为若要改变UI值 只能在主线程中。解决办法是应用Handler 代码修改最终如下:

[code=java]
new Thread(new Runnable() {
                
                @Override
                public void run() {
                    String path = "http://192.168.0.133:8080/Brower/index.html";    
                        try {              
                            URL url = new URL(path);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    
                            InputStream inStream = conn.getInputStream();                           
                            //byte[] data = StreamTool.read(inStream);
                            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int len = 0;
                            while( (len = inStream.read(buffer)) != -1){
                                outStream.write(buffer, 0, len);
                            }                        
                            html = new String(outStream.toByteArray(), "UTF-8");
                             Message msg = new Message();
                                msg.what = 100;
                            mHandler.sendMessage(msg);
                        } catch (Exception e) {            
                            Log.i("MainActivity", "ooo");
                        }        
                }
            }).start();
                        
        }  
        
        private Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case 100:
                    codeView.setText(html);
                    break;
                default:
                    break;
                }
            }            
        };


[/code]