Aug 17, 2011

Handle Web Exception raised from HttpWebRequest in C#

The HttpWebRequest and HttpWebResponse classes from the .NET Base Class Library make it easy to access Internet resources through a request/response model. The Httprequest object identifies the Web page to get and contains a GetResponse() method for obtaining a HttpWebResponse object. With a HttpWebResponse object, we retrieve a stream and extract page information using stream operations. If you are getting exception on GetResponse, see following code to get reason of error why it's happening.


try
        {
// Here we create the request and write the POST data to it.
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (HttpStatusCode.OK == response.StatusCode)
            {
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                ret = reader.ReadToEnd();
                response.Close();
            }

        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                {
                    string text = new StreamReader(data).ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }

You will get reason of exception(if there) in text variable and can fix easily.

Note: the HttpWebResponse.GetResponseStream() that you get from the WebException.Response is not the same as the response stream that you would have received from server.

It's really helpful to figure out or understand the web exception. You might also like to read Tools to view HTTP requests and responses and View HTTP requests and responses with Firebug.