C#下载网页(包含网页错误的情况)
2018-07-20 来源:open-open
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; }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:C#操作MySql数据库范例代码
下一篇:C# 执行外部命令
最新资讯
热门推荐