Matthias Shapiro

microsoft windows phone evangelist, infovis enthusiast

HttpWebRequest (WebClient) And Tombstoning in Windows Phone 7

My initial concern here was to deal with tombstoning when it comes to HTTP requests, because that issue has kicked my butt on more than one account. But the second thing you’ll find here is a simple pattern for HTTP requests and responses in Windows Phone 7.

Most of the .NET code I look at uses WebClient to do HTTP requests. But using WebClient can negatively affect the UI thread in Windows Phone 7, so we have to do something a little more like this:

   1:  public void MakeSomeHTTPCall()
   2:  {
   3:      var request = (HttpWebRequest)WebRequest.Create("http://my.awesomewebsite.com");
   4:      request.Method = "GET";
   5:      request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
   6:  }

Easy enough, right?

Not so fast!

If the user starts a request and then hits the “power” button on their phone, this will cancel that request. How can we tell when this has happened?

Well, we handle the response to this request in the “GetSomeResponse” method, so let’s take a look at that.

   1:  private void GetSomeResponse(IAsyncResult MyResultAsync)
   2:  {
   3:      HttpWebRequest request = (HttpWebRequest)MyResultAsync.AsyncState;
   4:      try
   5:      {
   6:          HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResultAsync);
   7:          if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 0)
   8:          {
   9:              using (StreamReader sr = new StreamReader(response.GetResponseStream()))
  10:              {
  11:                  // This result string below is going to be whatever I get back,
  12:                  //   be it JSON or XML or whatever
  13:                  string result = sr.ReadToEnd();                        
  14:              }
  15:          }
  16:      }
  17:      catch (WebException e)
  18:      {
  19:          if (e.Status == WebExceptionStatus.RequestCanceled)
  20:              MessageBox.Show("Looks like your request was interrupted by tombstoning");
  21:          else
  22:          {
  23:              using (HttpWebResponse response = (HttpWebResponse)e.Response)
  24:              {
  25:                  MessageBox.Show("I got an http error of: " + response.StatusCode.ToString());
  26:              }
  27:          }
  28:      }
  29:  }

OK… let’s walk through this.

First, we get our request from the MyResultAsync.AsyncState (line 3), which we’ use to get our response (line 6). Now we can get a HTTP status code (like “200 – OK” or “404 – Not Found”) from this response, right?

No, we cannot. If the response is something other than OK, it will trigger an error and we will jump to the “catch” with a WebException error (line 17).

If we’re coming back from a tombstone (or Fast Application Switching, which will also cancel the request), the WebException status will be “RequestCanceled”. We test for that case and do something special for it (depending on the app, we may want to automatically re-do the request to ensure that we don’t put the user out of sorts by an errant power button press). Otherwise, we know it’s a normal HTTP status code and we can deal with it that way.

9 Responses to HttpWebRequest (WebClient) And Tombstoning in Windows Phone 7

  1. WebClient no longer triggers callbacks on the UI thread if the app is built with the 7.1 SDK.

  2. Pingback: Dew Drop – January 12, 2012 (#1,240) | Alvin Ashcraft's Morning Dew

  3. Pingback: WindowsDevNews.com

  4. Pingback: HttpWebRequest und Tombstoning in WP7 « Pocketmobile's Blog

  5. Gaurav

    Thanks! Helped me out in handling the power off scenario.

  6. Pingback: #wp7dev in the last month | Windows Phone User Group

  7. Thanks a lot. This helped my clear my doubt although am getting some errors but i’ll correct them.

  8. Gary

    Exactly what I was looking for. Thanks for taking the time to post this.

  9. cent

    Thank you, man. Really helped!

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>