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(
"https://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);
}
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
Comments
- Anonymous
April 04, 2013
Great and most timely article. I was looking for exactly this. Do you know if the HttpClient beta is "Go Live"? Thanks!Dave - Anonymous
July 08, 2014
Can you please guide me with the sample how to send the data to the server which is waiting.. using the Http Post method