C#下載網頁(包含網頁錯誤的情況)
C#下載網頁,即使網頁404或者500錯誤
public static string GetWebPageAsString(string url) { HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url); HttpWebResponse httpWebResponse = null; string xml = ""; try { httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse(); } catch (WebException exception) { if (exception.Status == WebExceptionStatus.ProtocolError) { //get the response object from the WebException httpWebResponse = exception.Response as HttpWebResponse; if (httpWebResponse == null){ return "<Error />";} } } Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.ASCII); xml = streamReader.ReadToEnd(); //streamReader.Close(); if (httpWebResponse.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(xml); }return xml;
}</pre>
本文由用戶 wen5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!