Cédric Boivin
Cédric Boivin

Reputation: 11361

What's wrong with my HttpWebRequest

I dont know what are missing in my code.

If I call an 404 url my code get an exception.

HttpWebRequest req = WebRequest.Create(args.Url) as HttpWebRequest;
req.AllowAutoRedirect = true;
req.Timeout = args.TimeOut;
req.UserAgent = args.UserAgent;   
HttpWebResponse answer = req.GetResponse() as HttpWebResponse;
objResult.Status =answer.StatusCode;
Stream stream = answer.GetResponseStream();

I get an exception on req.GetResponse()

There is the error i get back

The remote server returned an error: (404) Not Found.

I am not suppose to received HttpStatusCode.NotFound ?

The solution :

try
      {
        HttpWebRequest req = WebRequest.Create(args.Url) as HttpWebRequest;
        req.AllowAutoRedirect = true;
        req.Timeout = args.TimeOut;
        req.UserAgent = args.UserAgent;       
        HttpWebResponse answer = req.GetResponse() as HttpWebResponse;

        objResult.Status =answer.StatusCode;       
      }
      catch (WebException ex)
      {
        HttpWebResponse response = ex.Response as HttpWebResponse;
        objResult.Status = response.StatusCode;       
      }

Upvotes: 1

Views: 2307

Answers (1)

SLaks
SLaks

Reputation: 888107

HttpWebRequest throws an exception on non-successful response statuses.
This behavior is by design.

You can get the response by catching a WebException and checking its Response property.

Upvotes: 3

Related Questions