C# HttpWebRequest ignore HTTP 500 error

放肆的年华 提交于 2021-02-04 13:32:47

问题


I'm trying to download a page using the WebRequest class in C#4.0. For some reason this page returns all the content correctly, but with a HTTP 500 internal error code.

Request.EndGetResponse(ar);

When the page returns HTTP 500 or 404, this method throws a WebException. How can I ignore this? I know it returns 500 but I still want to read the contents of the page / response.


回答1:


You can a try / catch block to catch the exception and do additional processing in case of http 404 or 500 errors by looking at the response object exposed by the WebExeption class.

try
{
    response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (System.Net.WebException ex)
{
    response = (HttpWebResponse)ex.Response;

    switch (response.StatusCode)
    {
        case HttpStatusCode.NotFound: // 404
            break;

        case HttpStatusCode.InternalServerError: // 500
            break;

        default:
            throw;
    }
}



回答2:


try {
    resp = rs.Request.EndGetResponse(ar);
} 
catch (WebException ex) 
{ 
    resp = ex.Response as HttpWebResponse; 
}



回答3:


Use a try / catch block to allow your program to keep running even if an exception is thrown:

try
{
    Request.EndGetResponse(ar);
}
catch (WebException wex)
{
    // Handle your exception here (or don't, to effectively "ignore" it)
}

// Program will continue to execute



回答4:


The problem is due to not sending browser details to the requesting site. you need to identify yourself to the website you are requesting the data.

simple add a useragent to your code

request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";

The end code should look something like this:

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(http://WEBURL);
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
try
{
response = (HttpWebResponse)Request.EndGetResponse(ar);
}
catch (System.Net.WebException ex)
{
response = (HttpWebResponse)ex.Response;

switch (response.StatusCode)
{
    case HttpStatusCode.NotFound: // 404
        break;

    case HttpStatusCode.InternalServerError: // 500
        break;

    default:
        throw;
}
}

Please find the reference/ proof for the mentioned above code: https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx

This was mentioned in the link

"A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing."



来源:https://stackoverflow.com/questions/3882323/c-sharp-httpwebrequest-ignore-http-500-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!