How can I get Http Status Code?

  • Thread starter Thread starter Jon Maz
  • Start date Start date
J

Jon Maz

Hi All,

Here's the code:

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.asdfasdfasdfafsd.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Response.Write(HttpWResp.StatusCode);

Here's what I would like it to return to me:
HTTP/1.1 400 Bad Request

And here's what it actually gives me:
The underlying connection was closed: The remote name could not be
resolved.

Any ideas how I can get the 400 code returned?

Thanks,


JON
 
Jon Maz said:
Here's the code:

HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.asdfasdfasdfafsd.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Response.Write(HttpWResp.StatusCode);

Here's what I would like it to return to me:
HTTP/1.1 400 Bad Request

And here's what it actually gives me:
The underlying connection was closed: The remote name could not be
resolved.

Any ideas how I can get the 400 code returned?

Hang on a sec - does www.asdfasdfasdfafsd.com exist and return that
response, or does it genuinely not exist? If it's the latter, there
*is* no 400 code to be returned - it couldn't even send the request, so
it can't get back a response code.
 
Yeah but you can't get a response from a server that doesn't exist (or one
you can't connect to) - which is the problem here (the name cannot be
resolved)... It's just not going to happen. You need to catch the exception.

Jerry
 
Exactly right - but the StatusCode property is in the HttpWebResponse, not
in the Exception!

Any ideas?

JON
 
Jon Maz said:
Exactly right - but the StatusCode property is in the HttpWebResponse, not
in the Exception!

Any ideas?

The WebException will contain a WebResponse.
 
But WebException.Response is of type WebResponse, which doesn't have a
StatusCode property (only HttpResponse or HttpWebResponse do).

I did just try casting it into an HttpWebResponse and getting the StatusCode
that way, but it didn't work.

Cheers,

JON
 
Actually although the documentation it says it's of type WebResponse, and
the IDE reacts as if it is a WebResponse, it actually seems to *be* an
HttpWebResponse.

More importantly, I have now got it working - thanks for the help!

JON
 
Jon Maz said:
Actually although the documentation it says it's of type WebResponse, and
the IDE reacts as if it is a WebResponse, it actually seems to *be* an
HttpWebResponse.

Yes - and that makes perfect sense, as an HttpWebResponse *is* a
WebResponse.
More importantly, I have now got it working - thanks for the help!

Goodo.
 
Back
Top