android 获取网页代码

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:hint="请输入路径"
        android:text="http://192.168.1.134:8080/" />

    <Button
        android:id="@+id/bt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="查看html" />

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

        <LinearLayout
            android:id="@+id/ll_loading"
            android:visibility="invisible"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="正在获取数据...." />
        </LinearLayout>

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

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

</LinearLayout>

StreamTools.java

package com.itheima.htmlviewer;

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

public class StreamTools {
	
	/**
	 * 把流里面的内容 转化成字符串
	 * @param is
	 * @return
	 */
	public static String readFromStream(InputStream is){
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024]; // 服务器返回的 0011 gbk的方式编码集
			int len = 0;
			while((len = is.read(buffer))!=-1){
				baos.write(buffer, 0, len);
			}
			is.close();
			byte[] result = baos.toByteArray();
			String newstr = new String(result);
			if(newstr.contains("charset=utf-8")){
				return newstr;
			}else if(newstr.contains("charset=gbk")){
				return new String(result,"gbk");
			}
			
			return newstr;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}

MainActivity.java

package com.itheima.htmlviewer;

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

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

public class MainActivity extends Activity {
	protected static final int LOAD_ERROR = 1;
	protected static final int LOAD_SUCCESS = 2;
	protected static final int LOAD_FINISH = 3;
	private EditText et_path;
	private TextView tv_content;
	private LinearLayout ll_loading;
	private Button bt;

	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_ERROR:
				Toast.makeText(MainActivity.this, "获取数据失败", 1).show();
				break;

			case LOAD_SUCCESS:
				String text = (String) msg.obj;
				tv_content.setText(text);
				break;
			case LOAD_FINISH:
				ll_loading.setVisibility(View.INVISIBLE);
				bt.setEnabled(true);
				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);
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        bt = (Button) findViewById(R.id.bt);
    }

    
    public void click(View view){
    	final String path = et_path.getText().toString().trim();
    	if(TextUtils.isEmpty(path)){
    		Toast.makeText(this, "路径不能为空", 1).show();
    		return;
    	}
    	
    	ll_loading.setVisibility(View.VISIBLE);
    	bt.setEnabled(false);
    	new Thread(){
    		public void run() {
    			try {
    				Thread.sleep(5000);
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");
					int code = conn.getResponseCode();
					if(code ==200){
						InputStream is = conn.getInputStream();
						//把他对应的字符串 显示到界面上.
						String text = StreamTools.readFromStream(is);
						Message msg = Message.obtain();
						msg.obj = text;
						msg.what = LOAD_SUCCESS;
						handler.sendMessage(msg);
					}else{
						//服务器 资源错误.
						Message msg = Message.obtain();
						msg.what = LOAD_ERROR;
						handler.sendMessage(msg);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what = LOAD_ERROR;
					handler.sendMessage(msg);
				}finally{
					Message msg = Message.obtain();
					msg.what = LOAD_FINISH;
					handler.sendMessage(msg);
				}
    			
    		};
    	}.start();
    	
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.htmlviewer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.htmlviewer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值