欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)下載網(wǎng)頁HTML源碼的方法

 更新時間:2014年09月15日 10:00:30   投稿:shichen2014  
這篇文章主要介紹了C#實(shí)現(xiàn)下載網(wǎng)頁HTML源碼的方法,是一個非常實(shí)用的技巧,還包含了對于下載失敗的判斷等邏輯處理,需要的朋友可以參考下

本文實(shí)例講述了C#實(shí)現(xiàn)下載網(wǎng)頁HTML源碼的方法。分享給大家供大家參考之用。具體方法如下:

public static class DownLoad_HTML
{
private static int FailCount = 0; //記錄下載失敗的次數(shù)

public static string GetHtml(string url) //傳入要下載的網(wǎng)址
{
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 網(wǎng)頁文字編碼
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 + "次,是否要繼續(xù)嘗試?" + Environment.NewLine + ex.ToString(), "數(shù)據(jù)下載異常", 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; //如果能執(zhí)行到這一步就表示下載終于成功了
return str;
}

希望本文所述對大家的C#程序設(shè)計有所幫助

相關(guān)文章

最新評論