2017-02-16 76 views
1

下載HTML當我試圖用這個方法來下載HTML:無法在Android Studio中

public class DownloadHtml extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     String result = ""; 
     URL url; 
     HttpURLConnection connection = null; 
     try { 
      url = new URL(urls[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      InputStream inputStream = connection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(inputStream); 
      int data = reader.read(); 
      while (data != -1) { 
       char currentChar = (char) data; 
       result += currentChar; 
       data = reader.read(); 
      } 
      return result; 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return "Failed"; 
     } 
    } 
} 

和記錄結果

 DownloadHtml downloadHtml = new DownloadHtml(); 
    String result = null; 
    try { 
     result = downloadHtml.execute("http://stackoverflow.com").get(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    Log.i("Html", result); 

我剛開的它只是很小的一部分。 有沒有辦法獲得整個網頁的HTML?

+0

你的代碼應該工作(效率低下)。請記住,許多頁面都有大量內容,這些內容是使用JavaScript動態生成的,您的代碼無法處理。 –

+0

是的,我注意到它很慢,最終我有一個名稱和圖像的網頁,我必須鏈接到圖像和名稱。所以爲了做到這一點,我想分別獲取整個html和Pattern獲取鏈接和名稱 – Jbwz

回答

0

解決方案很簡單。看起來Log.i不會一次打印所有內容。 當我試圖從HTML獲取所有鏈接時,它們已成功打印。