HttpWebResponse returns 404 error
Asked Answered
C

3

5

How to let Httpwebresponse ignore the 404 error and continue with it? It's easier than looking for exceptions in input as it is very rare when this happens.

Champaigne answered 7/12, 2009 at 2:44 Comment(0)
C
33

I'm assuming you have a line somewhere in your code like:

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Simply replace it with this:

HttpWebResponse response;

try
{
    response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    response = ex.Response as HttpWebResponse;
}
Circumambulate answered 7/12, 2009 at 3:8 Comment(6)
I meant to read the 404 document as if it was a normal because I'm parsing it, it just won't go through regexes...Champaigne
Yes, this will do just that. After this block of code executes, response will be the response stream from whatever was returned, no matter what the HTTP status code is.Circumambulate
Remeber that HttpWebResponse is IDisposable and needs to be wrapped in using block, otherwise you will hit concurrent http request limit.Selfpossessed
Instead of the using calling response.Close() is enough?Presumptuous
Adam, this solved my issue, but why does it work? If it isn't found, how can it be in the exception details? Well known Microsoft secret?Burble
@jp2code so just because a resource isn't found by the server doesn't mean it doesn't respond with something. Typically, when a response has a 404 Not Found status, the response body contains some information (maybe an error message or some other details). My answer also allows you to get the response body for other error status codes, so that you can get to whatever error information the server chooses to share with you.Circumambulate
S
10
    try
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mysite.com");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();          
    }
    catch(WebException ex)
    {
        HttpWebResponse webResponse = (HttpWebResponse)ex.Response;          
        if (webResponse.StatusCode == HttpStatusCode.NotFound)
        {
            //Handle 404 Error...
        }
    }
Steno answered 7/12, 2009 at 2:49 Comment(1)
I meant to read the 404 document as if it was a normal because I'm parsing it, it just won't go through regexes...Champaigne
O
0

If you look at the properties of the WebException that gets thrown, you'll see the property Response. Is this what you are looking for?

Overbold answered 7/12, 2009 at 2:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.