实例112:获取某个指定网页的HTML源码

来源:互联网 发布:小米批量卸载软件 编辑:程序博客网 时间:2024/05/01 18:28

这个实例是《Android开发实例大全》(第二版)中的。

关于这本书啊,我真是。。。。。


1.布局,简单的一个EditTex、一个Button,一个TextView(因为显示的代码太长了,就用一个ScrollView把它包起来了)。

<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" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="获得该地址网页的HTMl代码" />        <EditText         android:id="@+id/edit"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="http://www.baidu.com"        />        <Button         android:id="@+id/get_html"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="get Html"        android:gravity="center"        />        <ScrollView         android:layout_width="fill_parent"        android:layout_height="wrap_content"        >        <TextView         android:id="@+id/text"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        />    </ScrollView></LinearLayout>

2.准备工作之—— 一个工具类,用来读取流。

public class StreamTool {static byte[] read(InputStream inStream) throws Exception{ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while((len = inStream.read(buffer)) != -1 ){outputStream.write(buffer, 0, len);}inStream.close();return outputStream.toByteArray();}}

准备工作之—— 建立连接,获得指定网页的Html代码。采用写在MainActivity中的内部类。

public static class HttpService{public static String getHtml(String path) throws Exception{HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();//用path新建URL,建立连接conn.setConnectTimeout(5000);//设置超时时间conn.setRequestMethod("GET");if (conn.getResponseCode() == 200) {InputStream inStream = conn.getInputStream();byte[] data = StreamTool.read(inStream);//用之前的工具类方法来读取流return new String(data);}return null;}}

准备工作之——把这个方法 public static String getHtml(String path) 异步调用。(方式不一,Handler,Thread,Asynctask)这里用AsyncTask。也是内部类

本来不异步调用来着,结果会报NetworkOnMainThreadException。


3.Activity中的操作,准备工作做好之后就不难啦。
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mEditText  = (EditText)findViewById(R.id.edit);mButton    = (Button)findViewById(R.id.get_html);mTextView  = (TextView)findViewById(R.id.text);mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {GetHtmlAsnc getHtmlAsnc = new GetHtmlAsnc();getHtmlAsnc.execute();}});}
4.对了。别忘了在Manifest文件中加入权限。
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>





0 0
原创粉丝点击