public static Class Download_html
{
private static int failcount = 0; Record the number of failed downloads
public static string gethtml (string URL)//incoming URL to download
{
String str = string. Empty;
Try
{
System.Net.WebRequest request = System.Net.WebRequest.Create (URL);
Request. Timeout = 10000; Download time-out
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 Web Text encoding
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 ("Downloaded failed" + Failcount + "times, do you want to continue trying? "+ Environment.NewLine + ex. ToString (), "Data download Exception", 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 ("Download HTML failed" + Environment.NewLine + ex.) ToString (), "Download HTML failed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
Throw ex;
}
}
Else
{
str = gethtml (URL);
}
}
Failcount = 0; If you can perform this step, the download is finally successful.
return str;
}
}
C # download HTML source page