捕捉网页出现404、500等会直接抛出WebException异常
异常代码:
(HttpWebResponse)req.GetResponse();
当执行这段代码出现异常
解决问题
那如果我们想获得错误发生时候服务器段错误页面的源代码该如何做呢?
其实非常非常简单的做法,我们用下面的代码就不论错误发生与否,都可以获得服务器段页面的源代码。
public string HttpPost(string Url, string postDataStr, string ContentType = "application/x-www-form-urlencoded", string Headers = "", string codingStr = "gb2312") { string retString = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = ContentType; byte[] buffer = Encoding.UTF8.GetBytes(postDataStr); request.ContentLength = buffer.Length; if (!string.IsNullOrEmpty(Headers)) { var headersArry = Headers.Split('&'); for (int i = 0; i < headersArry.Length; i++) { request.Headers.Add(headersArry[i].Split('|')[0], headersArry[i].Split('|')[1]); } } using (Stream myRequestStream = request.GetRequestStream()) { myRequestStream.Write(buffer, 0, buffer.Length); myRequestStream.Close(); } HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); //获取响应内容 using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(codingStr))) { retString = myStreamReader.ReadToEnd(); } myResponseStream.Close(); return retString; }
当异常发生事后,WebException 中不仅有 StatusCode 标志着 HTTP 的错误代码,而且它的 Response 属性还包含由服务器发送的 WebResponse,来指示遇到的实际 HTTP 错误。