获取网络文本查看器--HTML源码

<span style="font-size:24px;">package com.melody.html;

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

import com.melody.html.tool.Tools;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Button bt;
	private TextView tv;
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			tv.setText((String) msg.obj);
		};
	};
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	public void click(View v){
		final String path = "http://192.168.119.69/baidu1.html";
		
		Thread t = new Thread(){		
			
			public void run() {			
				
				try {
					//1.创建URL对象
					URL url = new URL(path);
					//2.获取连接对象,进行设置
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					//3.设置属性
					conn.setRequestMethod("GET");
					conn.setReadTimeout(8000);
					conn.setReadTimeout(8000);
					//4.判断求情码是否成功,
					if(conn.getResponseCode() == 200){
						//获取服务器返回的输入流
						InputStream is = conn.getInputStream();
						//使用自定义方法获取流里的数据
						String text = Tools.getTextFromStrem(is);
						
						//发送消息至消息队列,主线程执行handlemessage,来刷新UI
						Message msg = handler.obtainMessage();
						msg.obj = text;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			
		};
		t.start();
		
		
		
		
		
		
	}
	//初始化控件
	private void init() {
		tv = (TextView) findViewById(R.id.tv);
	}
	
	
}
</span>

////////////////////////////////////////////////新建工具类////////////////////////////////////

<span style="font-size:24px;">package com.melody.html.tool;

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

/**
 * 从流中获取文本工具类
 * @author Administrator
 *
 */
public class Tools {
	
	public static String getTextFromStrem(InputStream is){
		byte[] b = new byte[1024];  //定义一个1K的字节数组
		int len;									//定义数组长度
		
		//定义一个字节数组输出流,保存数据   写入数据所以用输出流  读入写出
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		//开始往bos字节数组写入数据    
		try {
			while((len = is.read(b)) != -1){
				bos.write(b, 0, len);    
			}
			//把字节数组输出流转换成字节数组,然后用字节数组构造一个字符串
			//String text = new String(bos.toByteArray(),"GBK");   //指定文件编码  如果乱码的话这里改,默认UTF-8
			String text = new String(bos.toByteArray());
			return text;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

}
</span>
//////////////////////////////////添加权限//////////////////////////////////
<span style="font-size:24px;"> <uses-permission android:name="android.permission.INTERNET"/></span>


你可能感兴趣的:(获取网络文本查看器--HTML源码)