Android-html源代码的获取

来源:互联网 发布:上海爱回收java 编辑:程序博客网 时间:2024/05/21 06:24
首先要说的是要实现一个链接的html源代码的获取,在你的AndroidMainifest.xml中一定配置有以下两句的内容

<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
这样才能获取相应的网页代码,这两句话重要就是:1、一个负责连接网页。2、一个负责读取源代码

相关的类有:Handler(承担着子线程和主线程之间的通信)、Message(向Handler传递信息)、HttpURLConnection(实现简单的基于URL请求、响应功能)、还有一些IO流


MainActivity.java

package com.example.myhtmlview;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import javax.net.ssl.HttpsURLConnection;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.text.method.ScrollingMovementMethod;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private Button button;private EditText path;private TextView text;private String t=null;private Handler myhandler;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        path = (EditText)findViewById(R.id.uu);                text = (TextView)findViewById(R.id.text);        button =(Button)findViewById(R.id.buttton1);                text.setMovementMethod(ScrollingMovementMethod.getInstance());        button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubfinal String url=path.getText().toString();Toast.makeText(MainActivity.this, "成功获得链接"+url, Toast.LENGTH_SHORT).show();        Thread th = new Thread(){        public void run() {try {t=GetHtml(url);        Message m = new Message();        if(t!=null){        m.what=0x111;//用户自定义的消息代码        myhandler.sendMessage(m);//发送信息        }else{        m.what=0x110;        myhandler.sendMessage(m);        return;        }} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}        }        };        th.start();myhandler = new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubif(msg.what==0x111){text.setText(t);}else{Toast.makeText(MainActivity.this, "失败,请检查网络", Toast.LENGTH_SHORT).show();}super.handleMessage(msg);}};}});    }    public static String getHtml(String path) throws Exception{//将path包装成一个URL对象    URL url=new URL(path);    //取得链接对象(基于HTTP协议链接对象)    HttpURLConnection conn=(HttpURLConnection) url.openConnection();    //设置超时时间    conn.setConnectTimeout(5000);    //设置请求方式    conn.setRequestMethod("GET");    //判断请求是否成功(看一下getResponseCode)    if(conn.getResponseCode()==200){    InputStream instream=conn.getInputStream();    //流的工具类,专门从流中读取数据(返回的是二进制数据)    byte[] data=StreamTool.read(instream);    String html= new String(data,"UTF-8");    return html;         }return null;}}

注意:Toast.makeText(MainActivity.this, "成功获得链接"+url, Toast.LENGTH_SHORT).show();这句话是提示有没有获取到正确的url;但是需要注意的是不能随便放置,否则出错的


activity_main.xml

<LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:android="http://schemas.android.com/apk/res/android">    <LinearLayout         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        >    <EditText         android:id="@+id/uu"        android:layout_width="400dp"        android:layout_height="wrap_content"        />    <Button         android:id="@+id/buttton1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="搜索"        android:textSize="30sp"        />    </LinearLayout>    <TextView         android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="html"        android:textSize="25sp"        android:scrollbars="vertical"        /></LinearLayout>
StreamTool类
package com.example.myhtmlview;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool {/*     * 读取流中的数据     * */public static byte[] read(InputStream instream) throws Exception{ByteArrayOutputStream outStream=new ByteArrayOutputStream();//定义一个字节数组byte[] buffer=new byte[1024];//读满数组,就会返回(返回的是int型,代表读取的数组长度)//当返回值为-1时说明已经读完int len=0;while((len = instream.read(buffer)) !=-1){//buffer有多少数据就读多少outStream.write(buffer, 0, len);}instream.close();return outStream.toByteArray();}}





0 0