WP7: WebClient and HTTPWebRequest

Windows Phone 7 SDK has provided two classes for consuming resources from the web. WebClient and HTTPWebRequest.

HTTPWebRequest

HTTPWebRequest is a low level API for web requests. Unlike WebClient, it allows to tinker some of the HTTP aspects like cookies and user agent.

One major advantage of HTTPWebRequest is that it returns on another thread, which comes in handy for large web requests. It will not lock up the UI thread allowing the UI to remain responsive during the request. Since the response is returned on another thread the program should marshal the response back to the UI thread.

HTTPWebRequest is created by the static method HTTPWebRequest.Create().

Call the EndGetResponse() to get the WebResponse, which will contain the stream to read the response.

WebClient

WebClient is a higher level abstraction of the web request. It wraps the HTTPWebRequest to provide a more easier API to make web requests.

WebClient has a built in mechanism to report progress of the request in percentage. WebClient runs on the same thread, so programs don’t have to use the dispatcher to pass data back to the UI thread.

However, since the WebClient runs on the UI thread, it can make the UI unresponsive if the program makes a long running web request.

 

I think there is a place for using both the classes. Being aware of these differences helps to choose the best one for a given situation.

Windows Phone 7: Navigation

Web developers will find themselves in familiar territory with the navigation in Windows Phone 7.

NavigationService Class

Navigate to another page:

Navigate to another page (with parameters):

NavigationContext Class

If a parameter was passed to the destination page using query string, NavigationContext class allows to read the query string as follows

Navigation History

Navigation history is exposed as a read-only enumeration through the property called NavigationServices.BackStack,

There are additional methods exposed for going back and forward one step at a time. It is a good practice to check for the CanGoBack and CanGoForward property before calling the navigation methods to make sure there is more in the history to go back or forward.