您的位置:首页 > 移动开发 > Android开发

Android查看网页源码

2012-11-18 01:57 459 查看
1 布局

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


在ScrollView控件里嵌入一个TextView即可,其带有一个滚动条.

2利用网页的路径和编码方式,得到网页的字节数组

public class GetPageResource {
      public static String getHtml(String path,String encoding) throws Exception{
    	  HttpURLConnection connection=(HttpURLConnection) new URL(path).openConnection();
    	  connection.setConnectTimeout(5000);
    	  connection.setRequestMethod("POST");
    	 if(connection.getResponseCode()==200){
    		 InputStream inputStream=connection.getInputStream();
    		 byte [] imageData=GetResource.readResource(inputStream);
    		 return new String(imageData,encoding);
    	 }
    	 return null;
      }
}


分析:

(1)关于网页的编码方式,可以利用HttpWatch工具来获取

(2)利用URL得到HttpURLConnection connection这样便于资源建立起了联系,且设置connection的属性值

(3)利用HttpURLConnection connection得到输入流.即可以这么想:此时的网页已经保存到了此输入流inputStream里

(4)将在输入流里的网页数据输出到字节数组里面.即byte [] imageData=GetResource.readResource(inputStream).如下

readResource(inputStream)方法如下:

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


分析:

(1)没有方法可以把输入流里的数据直接放到字节数组里(查阅API即知),而是要利用ByteArrayOutputStream outputStream

把在输入流自己把自己的数据读(read())到一个字节数组里面,即inputStream.read(buffer),然后数组里面的数据放入

输出流ByteArrayOutputStream outputStream里面,即outputStream.write(buffer,0,len);

(2)待数据全部转移到输入流outputStream里面,此时就可以把输出流的数据全部转换为字节数组,即outputStream.toByteArray();

(3)在此例子就很好体现了输入流和输出流的使用.



在输入流相应的API中都是把输入流读取到一个数组中,或者只读取一个字节,或者读取一行

如FileInputStream类中的方法:

public int read(byte[] b,int off,int len)从此输入流中将最多 len 个字节的数据读入一个字节数组中

public int read()从此输入流中读取一个数据字节

如在BufferedReader类中的方法:

public String readLine() 读取一个文本行.返回值:包含该行内容的字符串

在输出流相应的API中都把是字节数组写入此输出流,或者只把数组中的某个位置的数据写入输出流

如ByteArrayOutputStream类的方法中:

public void write(byte[] b,int off,int len)将指定字节数组中从偏移量off开始的len个字节写入此字节数组输出流

public void write(int b)将指定的字节写入此字节数组输出流

然后我们可以发现:

(1)可以把输出流里的数据转换为字节数组

如ByteArrayOutputStream类的方法中:

public byte[] toByteArray():创建一个新分配的字节数组。其大小是此输出流的当前大小,并且缓冲区的有效内容已复制到该数组中。

(2)可以把输出流里的数据转换为字符串

如ByteArrayOutputStream类的方法中:

public String toString():将缓冲区的内容转换为字符串,根据平台的默认字符编码将字节转换成字符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: