C#下载网页HTML源码_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#下载网页HTML源码

C#下载网页HTML源码

 2014/9/15 3:12:50  小米营养粥  程序员俱乐部  我要评论(0)
  • 摘要:publicstaticclassDownLoad_HTML{privatestaticintFailCount=0;//记录下载失败的次数publicstaticstringGetHtml(stringurl)//传入要下载的网址{stringstr=string.Empty;try{System.Net.WebRequestrequest=System.Net.WebRequest.Create(url);request.Timeout=10000;//下载超时时间request
  • 标签: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;
}

}

上一篇: Spring MVC 学习笔记 json格式的输入和输出 下一篇: 没有下一篇了!
发表评论
用户名: 匿名