Using the HttpClient and the new System.Net.Http namespaces

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:

  • Helper methods that create requests and process the responses
  • The possibility of defining a default header to apply to all sent messages
  • Timeout and cancellation management

Getting ready

In order to use this recipe you should have Visual Studio 2012 installed.

How to do it...

Here we will create a basic application that exemplifies the clear usage of HTTPClient:

  1. First open Visual Studio 2012 and create a new project. We will select the Console Application template from the visual C# category and name it caHttpClient.
  2. Add a reference to the System.Net.Http assembly.
  3. Open Program.cs and add a using clause to the added assembly namespace:
    using System.Net.Http;
  4. Add the following method to perform a basic test of the new 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();
    }
  5. If we execute it, we will get the following result:
    How to do it...
  6. So we just have to increase the size of the response buffer.
  7. Before executing the HTTP petition, we will increase it with the following line:
    HttpCli.MaxResponseContentBufferSize = 512000;
  8. You can put in any value, but it is a common issue that the value entered is too small, so increasing the default response buffer is highly recommended, as we just did in the previous step.
  9. Next we will open the NuGet package manager by navigating to Tools | Library Package Manager | Manage NuGet Packages for Solution….
    How to do it...
  10. Once in the NuGet Package manager, locate and add the Microsoft ASP.NET Web API Client Libraries package. Adding this to our project will add the needed references, System.Net.Http.Formatting, System.Net.Http, and Newtonsoft.Json.
    How to do it...
  11. Add a using clause for the 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);
        }
    }
  12. Add the call to this function in the Main method and execute the application. We should get the flowing result:
    How to do it...

How it works...

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.

There's more...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset