Symptom
When a page is requestedCodeCode similar to the following:
Httpwebrequest Req = (httpwebrequest) webrequest. Create (strurl );
Req. useragent ="Msie6.0";
Req. method ="Get";
Httpwebresponse res = (httpwebresponse) Req. getresponse ();
Streamreader sr =NewStreamreader (res. getresponsestream (), strencode );
Strhtml = Sr. readtoend ();
Sr. Close ();
Res. Close ();
However, if the requested page is a page with an exception or does not exist. The above code will be
Req. getresponse ();
An exception is thrown here: the remote server returns an error: (500) internal server error.
Through the above Code, we cannot get the page when an error occurs.Source code.
Cause analysis:
(Httpwebresponse) Req. getresponse (); this line of code does the following:
When the server segment Asp.netProgramWhen an exception occurs, the client application receives an HTTP protocol error. Convert the HTTP protocol error to the webexception set to webexceptionstatus. protocolerror, and throw the exception.
Solve the problem
What should we do if we want to obtain the source code of the server segment error page when an error occurs?
In fact, it is very simple. We can use the following code to obtain the source code of the server segment page, regardless of whether an error occurs or not.
Httpwebresponse res;
Try
{
Res = (httpwebresponse) Req. getresponse ();
}
Catch(Webexception ex)
{
Res = (httpwebresponse) EX. response;
}
Streamreader sr =NewStreamreader (res. getresponsestream (), strencode );
Strhtml = Sr. readtoend ();
After an exception occurs, webexception contains not only the HTTP Error code but also the webresponse attribute sent by the server,
To indicate the actual HTTP Error.
The solution to this problem is so simple, but after I encountered this problem, I searched through Google and Baidu, and many people did not know it. So I organized this blog to help people who are troubled by this problem.
Appendix: derivative relationship diagram of httpwebrequest:
System. Object
System. externalbyrefobject
System. net. webrequest
System. Io. Packaging. packwebrequest
System. net. filewebrequest
System. net. ftpwebrequest
System. net. httpwebrequest
Refer:
How can I obtain error pages using WebClient?
Http://topic.csdn.net/t/20061030/17/5120137.html