Advertisement
ivandrofly

HttpClient is Here!

May 25th, 2014
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.48 KB | None | 0 0
  1. HttpClient is a modern HTTP client for .NET. It provides a flexible and extensible API for accessing all things exposed through HTTP. HttpClient has been available for a while as part of WCF Web API preview 6 but is now shipping as part of ASP.NET Web API and directly in .NET 4.5. You can also download it using NuGet – we just use the following three NuGet packages in this blog:
  2.  
  3. System.Net.Http: The main NuGet package providing the basic HttpClient and related classes
  4. System.Net.Http.Formatting: Adds support for serialization, deserialization as well as for many additional features building on top of System.Net.Http
  5. System.Json: Adds support for JsonVaue which is a mechanism for reading and manipulating JSON documents
  6. In case you haven’t played with HttpClient before, here is a quick overview of how it works:
  7.  
  8. HttpClient is the main class for sending and receiving HttpRequestMessages and HttpResponseMessages. If you are used to using WebClient or HttpWebRequest then it is worth noting that HttpClient differs in some interesting ways – here’s how to think about an HttpClient:
  9.  
  10. An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
  11. You can issue as many requests as you like through a single HttpClient instance.
  12. HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance.
  13. You can derive from HttpClient to create specialized clients for particular sites or patterns
  14. HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.
  15. Kicking the Tires
  16. We will be diving into lots of details in the near-future around features, extensibility, serialization, and more but let’s first kick the tires by sending a request to the World Bank Data Web API. Please see List of ASP.NET Web API and HttpClient Samples for the complete sample solution. The service provides all kinds of information about countries around the world. It exposes the data both as XML and as JSON but in this sample we download it as JSON and use JsonValue to traverse the request for interesting information without having to create a CLR type on the client side:
  17.  
  18. 1: /// <summary>
  19.    2: /// Sample download list of countries from the World Bank Data sources at http://data.worldbank.org/
  20.    3: /// </summary>
  21.    4: class Program
  22.    5: {
  23.    6:     static string _address = "http://api.worldbank.org/countries?format=json";
  24.    7:  
  25.    8:     static void Main(string[] args)
  26.    9:     {
  27.   10:         // Create an HttpClient instance
  28.   11:         HttpClient client = new HttpClient();
  29.   12:  
  30.   13:         // Send a request asynchronously continue when complete
  31.   14:         client.GetAsync(_address).ContinueWith(
  32.   15:             (requestTask) =>
  33.   16:             {
  34.   17:                 // Get HTTP response from completed task.
  35.   18:                 HttpResponseMessage response = requestTask.Result;
  36.   19:  
  37.   20:                 // Check that response was successful or throw exception
  38.   21:                 response.EnsureSuccessStatusCode();
  39.   22:  
  40.   23:                 // Read response asynchronously as JsonValue and write out top facts for each country
  41.   24:                 response.Content.ReadAsAsync<JsonArray>().ContinueWith(
  42.   25:                     (readTask) =>
  43.   26:                     {
  44.   27:                         Console.WriteLine("First 50 countries listed by The World Bank...");
  45.   28:                         foreach (var country in readTask.Result[1])
  46.   29:                         {
  47.   30:                             Console.WriteLine("   {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}",
  48.   31:                                 country.Value["name"],
  49.   32:                                 country.Value["iso2Code"],
  50.   33:                                 country.Value["capitalCity"],
  51.   34:                                 country.Value["latitude"],
  52.   35:                                 country.Value["longitude"]);
  53.   36:                         }
  54.   37:                     });
  55.   38:             });
  56.   39:  
  57.   40:         Console.WriteLine("Hit ENTER to exit...");
  58.   41:         Console.ReadLine();
  59.   42:     }
  60.   43: }
  61.  
  62. The HttpResponseMessage contains information about the response including the status code, headers, and any entity body. The entity body is encapsulated in HttpContent which captures content headers such as Content-Type, Content-Encoding, etc. as well as the actual content. The content can be read using any number of ReadAs* methods depending on how you would like to consume the data. In the sample above, we read the content as JsonArray so that we can navigate the data and get the information we want.
  63.  
  64. Trying out .Net 4.5
  65. An exciting feature in .NET 4.5 is the language support for asynchronous programming that makes programming Tasks even easier. Using the new async and await language keywords, we can replace the “ContinueWith” pattern in the sample above and get something that looks very clean like this:
  66.  
  67.  static string _address = "http://api.worldbank.org/countries?format=json";
  68.    2:  
  69.    3: static async void Run()
  70.    4: {
  71.    5:     // Create an HttpClient instance
  72.    6:     HttpClient client = new HttpClient();
  73.    7:  
  74.    8:     // Send a request asynchronously continue when complete
  75.    9:     HttpResponseMessage response = await client.GetAsync(_address);
  76.   10:  
  77.   11:     // Check that response was successful or throw exception
  78.   12:     response.EnsureSuccessStatusCode();
  79.   13:  
  80.   14:     // Read response asynchronously as JsonValue and write out top facts for each country
  81.   15:     JsonArray content = await response.Content.ReadAsAsync<JsonArray>();
  82.   16:  
  83.   17:     Console.WriteLine("First 50 countries listed by The World Bank...");
  84.   18:     foreach (var country in content[1])
  85.   19:     {
  86.   20:         Console.WriteLine("   {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}",
  87.   21:             country.Value["name"],
  88.   22:             country.Value["iso2Code"],
  89.   23:             country.Value["capitalCity"],
  90.   24:             country.Value["latitude"],
  91.   25:             country.Value["longitude"]);
  92.   26:     }
  93.   27: }
  94.   28:  
  95.   29: static void Main(string[] args)
  96.   30: {
  97.   31:     Run();
  98.   32:     Console.WriteLine("Hit ENTER to exit...");
  99.   33:     Console.ReadLine();
  100.   34: }
  101.  
  102. Source: http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement