The following code is used to make a request and get the results:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://bbrown.info/");
<p>
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
string contents = reader.ReadToEnd();
resp.Close();contents
will contain the HTML of this blog if the server gives a 200 OK
response. Anything else will throw a WebException
. You can wrap the snippet above in a try-catch to handle a non-200
, but the exception is thrown in the GetResponse
call so you get nothing from the actual response. 404
? May as well be a 500
.</p><p>Today I discovered that the WebException
itself has two properties: Response
and Status
. This Response
is the same as the resp
above so you can extract out the server response in the catch.</p><p>This whole behavior of HttpWebRequest
is counterintuitive in the sense that a non-200
is not an exceptional circumstance; I would have expected the response to be accessible and the status code to be populated.</p>