Async and Await for HTTP Networking, Part 2–HttpClient

In my previous post on this topic, Async and Await for Http Networking on Windows Phone, I described how you can use extension methods to create awaitable methods on the WebClient and HttpWebRequest APIs. Courtesy of Microsoft’s .NET Framework team, there have been more developments in this area – the creation of a portable implementation of the HttpClient API, until now available only for Windows 8 Store and .NET Framework 4.5 apps. This API will allow developers to consume HttpClient on Windows Phone 7.5 and higher, Windows Store apps, and .NET Framework 4.0 and higher.

Portable HttpClient for .NET Framework and Windows Phone

As they describe on their blog post here, the .NET Framework team have released a Beta release of the portable version of HttpClient, the modern networking API. The HttpClient library is a set of APIs for .NET which provide a flexible and extensible way to access all things exposed through HTTP. HttpClient exposes the new Task based asynchronous methods, which makes writing responsive and performant UI applications across all platforms a lot simpler.

This is particularly significant for anyone developing apps for both Windows Phone and Windows 8 as it allows you to standardise your networking code around HttpClient.  In addition it also enables other portable library developers who require networking support to use HttpClient while targeting all or a subset of the supported platforms.

To use it, first make sure you have got NuGet v2.1 or later installed (Go to Tools – Extensions and Updates). Then to use the HttpClient package, right click on your solution, go to the Manage Nuget Packages dialog, search for Id Microsoft.Net.Http, and make sure “Include Prerelease” is turned on.

Now you can go ahead and program against the HttpClient API. For example, here’s the code to access the OData feed for the Northwind sample feed at Odata.org:

HttpClient httpClient = new HttpClient();    
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
HttpResponseMessage response = null;
try
{            
    response = await httpClient.GetAsync(
        "http://services.odata.org/Northwind/Northwind.svc/Suppliers");

    response.EnsureSuccessStatusCode(); // Throws exception if bad HTTP status code
    Debug.WriteLine(response.StatusCode + " " + response.ReasonPhrase);

    string responseBodyAsText = await response.Content.ReadAsStringAsync();
    var feed = Newtonsoft.Json.JsonConvert.DeserializeObject<SupplierODataFeed>(responseBodyAsText);

    MessageBox.Show("Received payload of " + responseBodyAsText.Length + " characters");

    SuppliersList.ItemsSource = feed.d.results;
}
catch (HttpRequestException hre)
{
    MessageBox.Show("RespCallback Exception raised! Message:{0}" + hre.Message);
}

Using Compression with the Portable HttpClient

Anyone who knows me or has seen the Networking JumpStart video, will know that I am running a bit of  a crusade against the non-application of compression. Too many devs forget the simple fact that mobile apps on cellular networks (that’s not just Phone people – same for Windows 8 machines that have integrated cellular networking!) often find themselves trying to communicate over poor quality networks. Stack the cards in your favour, increase the chance of success and USE COMPRESSION!

Fortunately, many other people share my views on this. The excellent people at AdvancedREI have created the HttpClient.Compression NuGet package, based on original work by the super-excellent Morten Nielsen.

This is also a pre-release NuGet package. After you install that package, all you do is new up an instance of the CompressedHttpClientHandler and pass that into the constructor of HttpClient:

// Requires HttpClient.Compression NuGet package
var handler = new AdvancedREI.Net.Http.Compression.CompressedHttpClientHandler(); 

HttpClient httpClient = new HttpClient(handler); 

As long as your server is configured to serve up compressed content, you will receive data compressed over the wire and the handler will take care of decompression on receipt.

Download the sample code here

One thought on “Async and Await for HTTP Networking, Part 2–HttpClient

  1. Pingback: Cheatsheet: 2013 03.01 ~ 03.14 - iOS教程 - 开发者

Leave a Reply

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