C#实现下载网页HTML源码的方法

时间:2021-05-20

本文实例讲述了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#程序设计有所帮助

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章