C#下載網頁HTML源碼

來源:互聯網
上載者:User

標籤:io   os   ar   for   資料   sp   log   on   c   


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#下載網頁HTML源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.