2005-03-01

More on HttpWebResponse

The day is crawling by so slowly today, and I don't know why. It feels like it should be much later than it is. These are the worst days of all, where time just hangs off of your shoulders like a heavy, wet scarf.

I figured out that there's a compromise between HttpWebResponse returning a WebException (what it does) and HttpWebResponse returning a valid object with a status code not equal to "200 OK" (what it should do). You can simply ignore doing anything of consequence with the WebException and pack it into the response itself.

I was toying with this idea when I posted my first rant on the subject, but I didn't want to say anything until I'd written a little code to see if it would function.

  HttpWebRequest req = null;
  HttpWebResponse response = null;

  req = (HttpWebRequest) WebRequest.Create("http://some/file/somewhere.txt");

  // Almost always guaranteed to return a "304 Not Modified"
  req.IfModifiedSince = DateTime.Now;

  try {
    response = req.GetResponse();
  }
  catch (WebException we) {
    if (null == response) {
      response = we.Response;
    }
    else {
      return;
    }
  }

  try {
    switch (response.StatusCode) {
      case HttpStatusCode.OK:
        break;
      case HttpStatusCode.NotModified:
        throw new Exception("resource not modified");

      ...

      default:
        throw new Exception("response had unhandled status code");
    }
  }
  catch (Exception e) {
    // error-handling code goes here
    return;
  }

  do_something_with_the_response();

This is just one way to do it, I'm sure there are more. I'm mostly interested in having a consistent flow to the program: I don't want to break the flow up into handling all sorts of exceptions and shuffling around inside catch() blocks when a single switch() statement can hold every avenue the program can take depending on what the host says.

No comments: