Phenomenon
When we encode the implementation to request a page, the requested code resembles the following code:
1HttpWebRequest req =(HttpWebRequest) webrequest.create (strURL);2Req. UserAgent ="MSIE6.0";3Req. Method ="GET";4HttpWebResponse res =(HttpWebResponse) req. GetResponse ();5StreamReader sr =NewStreamReader (Res. GetResponseStream (), strencode);6strHTML =Sr. ReadToEnd ();7 Sr. Close ();8Res. 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
1 req. GetResponse ();
Exception thrown here: The remote server returned an error: (500) Internal server 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.
1 HttpWebResponse Res;2 Try3 {4res =(HttpWebResponse) req. GetResponse ();5 }6 Catch(WebException ex)7 {8res =(HttpWebResponse) ex. Response;9 }TenStreamReader sr =NewStreamReader (Res. GetResponseStream (), strencode); OnestrHTML = 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.
HttpWebResponse The remote server returned an error: (500) Internal server error.