• Android(java)学习笔记146:网页源码查看器(Handler消息机制)


    1.项目框架图:

    2.首先是布局文件activity_main.xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    
        <EditText
            android:id="@+id/et_path"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="http://192.168.1.100:8080/hello.jsp" />
    
        <Button
            android:onClick="click"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="查看源码" />
    
        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
    
            <TextView
                android:id="@+id/tv_result"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
        </ScrollView>
    
    </LinearLayout>

    3.MainActivity.java:

     1 package com.itheima.netsourceviewer;
     2 
     3 import java.io.InputStream;
     4 import java.net.HttpURLConnection;
     5 import java.net.URL;
     6 
     7 import android.app.Activity;
     8 import android.os.Bundle;
     9 import android.os.Handler;
    10 import android.os.Message;
    11 import android.view.View;
    12 import android.widget.EditText;
    13 import android.widget.TextView;
    14 import android.widget.Toast;
    15 
    16 import com.itheima.netsourceviewer.utils.StreamTools;
    17 
    18 public class MainActivity extends Activity {
    19     protected static final int SUCCESS = 1;
    20     protected static final int ERROR = 2;
    21     
    22     private EditText et_path;
    23     private TextView tv_result;
    24     
    25     private Handler handler = new Handler(){
    26         public void handleMessage(android.os.Message msg) {
    27             switch (msg.what) {
    28             case SUCCESS:
    29                 String text = (String) msg.obj;
    30                 tv_result.setText(text);
    31                 break;
    32             case ERROR:
    33                 Toast.makeText(MainActivity.this, "请求失败", 1).show();
    34                 break;
    35             }
    36         };
    37     };
    38 
    39     @Override
    40     protected void onCreate(Bundle savedInstanceState) {
    41         super.onCreate(savedInstanceState);
    42         setContentView(R.layout.activity_main);
    43         et_path = (EditText) findViewById(R.id.et_path);
    44         tv_result = (TextView) findViewById(R.id.tv_result);
    45     }
    46     /**
    47      * 查看源文件的点击事件
    48      * @param view
    49      */
    50     public void click(View view){
    51         final String path = et_path.getText().toString().trim();
    52         //访问网络,把html源文件下载下来
    53         new Thread(){
    54             public void run() {
    55                 try {
    56                     //获取url对象
    57                     URL url = new URL(path);
    58                     //获取链接对象
    59                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    60                     //获取请求方式,默认GET
    61                     conn.setRequestMethod("GET");//声明请求方式 默认get
    62                     //告诉服务器我是什么样的客户端
    63                     conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.3.3; zh-cn; sdk Build/GRI34) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/6.0.0.57_r870003.501 NetType/internet");
    64                     //获取状态吗
    65                     int code = conn.getResponseCode();
    66                     //判断状态吗
    67                     if(code ==200){
    68                         InputStream is = conn.getInputStream();
    69                         //使用工具类, 把字节输入流的数据编程字符串
    70                         String result = StreamTools.readStream(is);
    71                         
    72                         Message msg = Message.obtain();//减少消息创建的数量
    73                         msg.obj = result;
    74                         msg.what = SUCCESS;
    75                         handler.sendMessage(msg);
    76                     }
    77                 } catch (Exception e) {
    78                     Message msg = Message.obtain();//减少消息创建的数量
    79                     msg.what = ERROR;
    80                     handler.sendMessage(msg);
    81                     e.printStackTrace();
    82                 }
    83             };
    84         }.start();
    85     }
    86 }

     

    4.这里的工具类是StreamTools.java:

     1 package com.itheima.netsourceviewer.utils;
     2 
     3 import java.io.ByteArrayOutputStream;
     4 import java.io.IOException;
     5 import java.io.InputStream;
     6 
     7 /**
     8  * 流的工具类
     9  * @author Administrator
    10  *
    11  */
    12 public class StreamTools {
    13     /**
    14      * 把输入流的内容转换成字符串
    15      * @param is
    16      * @return null解析失败, string读取成功
    17      */
    18     public static String readStream(InputStream is) {
    19         try {
    20             ByteArrayOutputStream baos = new ByteArrayOutputStream();
    21             byte[] buffer = new byte[1024];
    22             int len = -1;
    23             while( (len = is.read(buffer))!=-1){
    24                 baos.write(buffer, 0, len);
    25             }
    26             is.close();
    27             String temptext = new String(baos.toByteArray());
    28             if(temptext.contains("charset=gb2312")){//解析meta标签
    29                 return new String(baos.toByteArray(),"gb2312");
    30             }else{
    31                 return new String(baos.toByteArray(),"utf-8");
    32             }
    33         } catch (IOException e) {
    34             e.printStackTrace();
    35             return null;
    36         }
    37     }
    38 }
  • 相关阅读:
    mybatis四大接口之 ParameterHandler
    mybatis四大接口之 Executor
    网络协议
    4、Android UI测试
    3、Android构建仪表测试
    【翻译】Ext JS 6.2 早期访问版本发布
    2、Android构建本地单元测试
    1、Android测试入门
    安卓中的事件分发机制源码解析
    安卓IPC机制之Binder详解
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4771031.html
Copyright © 2020-2023  润新知