Phenomenon
When we encode the implementation to request a page, the requested code resembles the following code:
HttpWebRequest req = (HttpWebRequest) webrequest.create (strURL);
Req. useragent = "MSIE6.0";
Req. Method = "GET";
HttpWebResponse res = (HttpWebResponse) req. GetResponse ();
StreamReader sr = new StreamReader (res. GetResponseStream (), Strencode);
strHTML = Sr. ReadToEnd ();
Sr. Close ();
However, if the page we are requesting is exactly a page with an exception, or a page that does not exist. The code above will be in
Req. GetResponse ();
Exception thrown here: The remote server returned an error: (400, a) error.
We pass the above code, is unable to get error occurs when the page source code.
Analysis Reason:
(HttpWebResponse) Req. GetResponse (); This line of code does something like this:
When a server segment ASP. Exception occurs, the client application accepts an HTTP protocol error. Convert this HTTP protocol error to the Status set to WebExceptionStatus.ProtocolError, and throw the exception out of the WebException.
Solve the problem
So what if we want to get the source code of the server Segment error page when the error occurs?
In fact, very very simple approach, we use the following code, regardless of whether the error occurs or not, you can get the server Segment page source code.
HttpWebResponse Res;
Try
{
res = (HttpWebResponse) req. GetResponse ();
}
catch (WebException ex)
{
res = (HttpWebResponse) ex. Response;
}
StreamReader sr = new StreamReader (res. GetResponseStream (), Strencode);
strHTML = Sr. ReadToEnd ();
When an exception occurs, not only does StatusCode mark the HTTP error code in WebException, but its Response property also contains the WebResponse sent by the server,
To indicate the actual HTTP error encountered.
The remote server returned an error: 404 error, the remote server returned an error: 500 error, HttpWebResponse the remote server returned an error: (404, 500) error.