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.
HttpWebResponse returns 404 error
Asked Answered
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;
}
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
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...
}
}
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
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?
© 2022 - 2024 — McMap. All rights reserved.