本文執行個體講述了C#實現下載網頁HTML源碼的方法。分享給大家供大家參考之用。具體方法如下:
public static class DownLoad_HTML{private static int FailCount = 0; //記錄下載失敗的次數 public static string GetHtml(string url) //傳入要下載的網址{string str = string.Empty;try{System.Net.WebRequest request = System.Net.WebRequest.Create(url);request.Timeout = 10000; //下載逾時時間request.Headers.Set("Pragma", "no-cache");System.Net.WebResponse response = request.GetResponse();System.IO.Stream streamReceive = response.GetResponseStream();Encoding encoding = Encoding.GetEncoding("gb2312");//utf-8 網頁文字編碼System.IO.StreamReader streamReader = new System.IO.StreamReader(streamReceive, encoding);str = streamReader.ReadToEnd();streamReader.Close();}catch (Exception ex){FailCount++; if (FailCount > 5){var result = System.Windows.Forms.MessageBox.Show("已下載失敗" + FailCount + "次,是否要繼續嘗試?" + Environment.NewLine + ex.ToString(), "資料下載異常", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error);if (result == System.Windows.Forms.DialogResult.Yes){str = GetHtml(url);}else{System.Windows.Forms.MessageBox.Show("下載HTML失敗" + Environment.NewLine + ex.ToString(), "下載HTML失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);throw ex;}}else{str = GetHtml(url);}} FailCount = 0; //如果能執行到這一步就表示下載終於成功了return str;}
希望本文所述對大家的C#程式設計有所協助