HttpClient
is a new .NET 4.5 class using the HTTP protocol, similar to WebClient
or HttpWebRequest
. A highlight of this class is the full support of Async.
In fact it's not such a novelty, since we already had it on the REST Starter Kit and the implementation of the .NET 4.0 We API.
The HttpClient
class resides on the System.Net.Http
namespace, which is a brand new .NET 4.5 namespace. Basically, we use HttpClient
to create HTTP requests, manage the response, and process the response's content.
Some of the most interesting capabilities are:
Here we will create a basic application
that exemplifies the clear usage of HTTPClient
:
caHttpClient
.System.Net.Http
assembly.Program.cs
and add a using
clause to the added assembly namespace:using System.Net.Http;
HttpClient
class:private static async Task TestHttpClient() { try { HttpClient HttpCli = new HttpClient(); Console.WriteLine("Executing the Asyncronous http petition "); HttpResponse MessageHttpResponse = await HttpCli.GetAsync("http://www.packtpub.com/"); HttpResponse.EnsureSuccessStatusCode(); string StringHttpResponse = await HttpResponse.Content.ReadAsStringAsync(); Console.WriteLine(StringHttpResponse); } catch (HttpRequestException e) { Console.WriteLine(" There was a problem.."); Console.WriteLine("Problem :{0} ", e.Message); } }
And call it from the Main
method:
static void Main(string[] args) { Console.WriteLine("Press a key to start "); Console.ReadLine(); TestHttpClient(); Console.ReadLine(); }
HttpCli.MaxResponseContentBufferSize = 512000;
System.Net.Http.Formatting
, System.Net.Http
, and Newtonsoft.Json
.Newtonsoft.Json
namespace and the following method:private static async Task TestHttpClientJson() { try { HttpClient HttpCli = new HttpClient(); HttpResponseMessage response = await HttpCli.GetAsync("http://api.worldbank.org/countries?format=json"); response.EnsureSuccessStatusCode(); JArray content = await response.Content.ReadAsAsync<JArray>(); return Console.WriteLine("First 10 World Bank countries:"); var i = 0; foreach (var country in content[1].Take(10)) { i = i + 1; Console.WriteLine(" - {0} : {1}", i, country.Value<string>("name")); } } catch (HttpRequestException e) { Console.WriteLine(" There was a problem.."); Console.WriteLine("Problem :{0} ", e.Message); } }
Main
method and execute the application. We should get the flowing result: We created a console application and added the System.Net.Http
assemblies and namespaces.
Then, we created an instance of the HttpClient
class, extended its maximum buffer size, and instanced a HttpResponseMessage
class that we used to capture the response from the HttpClient
class.
To fill the response message, we are using the GetAsync
method of the HttpClient
class. It is an Async
method, as most of the methods we can find on this namespace. It makes the code easy to read.
Alternatively, we could have used other read methods such as ReadByteArray
, GetStream
, or GetStringAsync
. In fact, the helper method GetStringAsync
could have been used as follows:
stringHttpStringResponse = await HttpCli.GetStringAsync(http://www.packtpub.com/);
Instead of:
HttpResponse MessageHttpResponse = await HttpCli.GetAsync("http://www.packtpub.com/"); HttpResponse.EnsureSuccessStatusCode(); string StringHttpResponse = await HttpResponse.Content.ReadAsStringAsync();
Additionally, we get the errors and validations from the response message; in this case we use the HttpResponseMessage
method to ensure that the response was successful and throw an error if not:
HttpResponse.EnsureSuccessStatusCode();
We are accessing the Content
property of the HttpResponseMessage
class to get the string value. This Content
is of type HttpContent
and, if needed, we could access its Headers
property and all its related properties such as Content-Language
, Content-T
e
, and Last-Modified
:
string StringHttpResponse = await HttpResponse.Content.ReadAsStringAsync();
Next, we write the content we got, in this case, our website's HTML content.
Additionally, we have expanded our basic hello HttpClient
by adding in some extension methods provided by System.Net.Http.Formatting
and some JSON built into .NET with Newtonsoft.Json
, both of them added with the Microsoft ASP.NET Web API Client Libraries NuGet package.
System.Net.Http.Formatting
provides us with support for serialization, deserialization, and some other features on top of System.Net.Http
.
Newtonsoft.Json
enhances JSON helper objects with functionalities to read and manipulate JSON documents such as JsonArray
and JsonToken
.
In this example, we get a URI that returns JSON data, and retrieve it with GetAsync
into an HttpResponseMessage
object:
HttpResponseMessage response = await HttpCli.GetAsync("http://api.worldbank.org/countries?format=json");
Next we read the HttpContent
page that we got from our response message with ReadAsAsync<JArray>()
:
JArraycontent = await response.Content.ReadAsAsync<JArray>();
This does the magic and we now have an array of JsonToken
elements that we can iterate through and write into the console.
By now, we should have a grasp of the power of HttpClient
and its related assemblies, but there's more than what we have seen.
HttpClient
provides us with a powerful API to access everything exposed through HTTP via GET
, POST
, PUT
, and DELETE
, which support the standard very well and also nicely match the WebAPI on the server side.