This article describes the C # implementation of the download page HTML source code method. Share it for everyone's reference. Here's how:
public static class Download_html{private static int failcount = 0;//record 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" + FAILC Ount + "times, do you want to continue to try? "+ Environment.NewLine + ex. ToString (), "Data download Exception", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error); (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 finally succeeds. return str;
Hopefully this article will help you with your C # program design