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()
3: var request = (HttpWebRequest)WebRequest.Create("http://my.awesomewebsite.com");
4: request.Method = "GET";
5: request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
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)
3: HttpWebRequest request = (HttpWebRequest)MyResultAsync.AsyncState;
6: HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResultAsync);
7: if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 0)
9: using (StreamReader sr = new StreamReader(response.GetResponseStream()))
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();
17: catch (WebException e)
19: if (e.Status == WebExceptionStatus.RequestCanceled)
20: MessageBox.Show("Looks like your request was interrupted by tombstoning");
23: using (HttpWebResponse response = (HttpWebResponse)e.Response)
25: MessageBox.Show("I got an http error of: " + response.StatusCode.ToString());
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.