Android获取网页源代码


1、首先在AndroidManifest中加入Internet权限:

 
  1. <!-- 访问网络的权限 -->  
  2.  <uses-permission android:name="android.permission.INTERNET"/>  

2、Activity中得代码如下:

 
  1. public class GetHtmlCodeActivity extends Activity {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.main);  
  6.           
  7.         TextView textView = (TextView)this.findViewById(R.id.picture_textview);  
  8.         try {  
  9.             textView.setText(getPictureData("http://www.baidu.com"));  
  10.         } catch (Exception e) {  
  11.             Log.e("GetHtmlCodeActivity", e.toString());  
  12.             Toast.makeText(GetHtmlCodeActivity.this"网络连接失败"1).show();  
  13.         }  
  14.     }  
  15.     //得到图片的二进制数据   
  16.     public String getPictureData(String path) throws Exception{  
  17.         // 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。   
  18.         URL url = new URL("http://www.baidu.com/");  
  19.         // 每个 HttpURLConnection 实例都可用于生成单个请求,   
  20.         //但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络   
  21.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  22.         //设置 URL 请求的方法   
  23.         conn.setRequestMethod("GET");  
  24.         //设置一个指定的超时值(以毫秒为单位),   
  25.         //该值将在打开到此 URLConnection 引用的资源的通信链接时使用。   
  26.         conn.setConnectTimeout(5 * 1000);  
  27.         // conn.getInputStream()返回从此打开的连接读取的输入流   
  28.         InputStream inStream = conn.getInputStream();// 通过输入流获取html数据   
  29.         byte[] data = readInputStream(inStream);// 得到html的二进制数据   
  30.         String html = new String(data);  
  31.         return html;  
  32.           
  33.     }  
  34.     //读取输入流中的数据,返回字节数组byte[]   
  35.     public byte[] readInputStream(InputStream inStream) throws Exception{  
  36.         //此类实现了一个输出流,其中的数据被写入一个 byte 数组   
  37.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  38.         // 字节数组   
  39.         byte[] buffer = new byte[1024];  
  40.         int len = 0;  
  41.         //从输入流中读取一定数量的字节,并将其存储在缓冲区数组buffer 中   
  42.         while ((len = inStream.read(buffer)) != -1) {  
  43.             // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流   
  44.             outStream.write(buffer, 0, len);  
  45.         }  
  46.         inStream.close();  
  47.         //toByteArray()创建一个新分配的 byte 数组。   
  48.         return outStream.toByteArray();  
  49.     }  
  50. }  

相关内容