【Android Demo】擷取指定網頁的頁面原始碼,androiddemo
1.直接上
2.代碼
主要就是工具類HtmlService.java:
import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/** * 擷取HTML資料 * * @author David * */public class HtmlService { public static String getHtml(String path) throws Exception { // 通過網路地址建立URL對象 URL url = new URL(path); // 根據URL // 開啟串連,URL.openConnection函數會根據URL的類型,返回不同的URLConnection子類的對象,這裡URL是一個http,因此實際返回的是HttpURLConnection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 設定URL的請求類別,有POST、GET 兩類 conn.setRequestMethod("GET"); //設定從主機讀取資料逾時(單位:毫秒) conn.setConnectTimeout(5000); //設定串連主機逾時(單位:毫秒) conn.setReadTimeout(5000); // 通過開啟的串連讀取的輸入資料流,擷取html資料 InputStream inStream = conn.getInputStream(); // 得到html的位元據 byte[] data = readInputStream(inStream); // 是用指定的字元集解碼指定的位元組數組構造一個新的字串 String html = new String(data, "utf-8"); return html; } /** * 讀取輸入資料流,得到html的位元據 * * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); }}
MainActivity.java 修改如下:
public class MainActivity extends Activity { private String path = "http://www.cnblogs.com/yc-755909659/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView)this.findViewById(R.id.textView); try { String htmlContent = HtmlService.getHtml(path); textView.setText(htmlContent); } catch (Exception e) { textView.setText("程式出現異常:"+e.toString()); } }}
activity_main.xml 很簡單,還是放上來吧
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" /></ScrollView>
最後,記得添加網路存取權限哦
<uses-permission android:name="android.permission.INTERNET"/>
來源:Android擷取HTML資料