1. 程式人生 > >android根據Url獲取訪問網頁的原始碼

android根據Url獲取訪問網頁的原始碼

/**
 * 獲取HTML資料
 * 
 * 
 */
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(); } }