(十三)网络html查看器

一:此节的重点部分:如何把输入流的数据转化为字符串功能的实现,详情见五:StreamTools.java。注意:访问网络一定要加权限:    <uses-permission android:name="android.permission.INTERNET" />

功能需求:在EditText输入网址,点击浏览将可以查看到一个网页的html文件。程序运行结果如下所示:

二:整个程序的结构图如下所示:

三、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="com.example.htmlview.MainActivity" >

    <EditText
        android:id="@+id/et_path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入网址"
        android:text="http://www.cnblogs.com/fuyanan/p/4080201.html" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="浏览" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </ScrollView>

</LinearLayout>

四、MainActivity.java代码如下所示:

package com.example.htmlview;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.example.htmlview.utils.StreamTools;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
protected static final int ERROR = 1;
protected static final int SHOW_TEXT = 2;
protected static final String TAG = "MainActivityHtml";
private EditText et_path;
private TextView tv_content;
private Handler handler=new Handler(){

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
        case ERROR:
            Toast.makeText(MainActivity.this, "获取网络资源失败", 1).show();
            break;
        case SHOW_TEXT:
            tv_content.setText((CharSequence) msg.obj);
            break;

        
        }
    }
    
};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path=(EditText)findViewById(R.id.et_path);
        tv_content=(TextView)findViewById(R.id.tv_content);
    }

    public void click(View view){
        final String path=et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "网络地址不能为空", 1).show();
            return;
        }else{
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        URL url=new URL(path);
                        Log.i(TAG, "getResponseCode"+ url);
                        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                        Log.i(TAG, "getResponseCode");

                        conn.setRequestMethod("GET");
                         conn.setConnectTimeout(5000);
                         int code=conn.getResponseCode();
                         if(code==200){
                             InputStream is=conn.getInputStream();  //得到服务器端返回来的输入流
                             String result=StreamTools.ReadInputStream(is);
                             Message msg=new Message();
                            msg.what=SHOW_TEXT;
                            msg.obj=result;
                            handler.sendMessage(msg);
                         
                         }else{
                              Log.i(TAG, "code != 200");
                             Message msg=new Message();
                            msg.what=ERROR;
                            handler.sendMessage(msg);
                         }
                        
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                         Log.i(TAG, "Exception");
                        e.printStackTrace();
                        Message msg=new Message();
                        msg.what=ERROR;
                        handler.sendMessage(msg);
                    }
                }
            }).start();
        }
    }
}

五、StreamTools.java文件

package com.example.htmlview.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;

public class StreamTools {

    /**
     * 把输入流的数据转化为字符串
     * 
     * @param is
     *            输入流
     * @return 字符串
     */
    public static String ReadInputStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            byte[] result = baos.toByteArray();
            return new String(result);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "将输入流转化为字符串失败";
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。