четверг, 10 октября 2013 г.

Http Client Introduction

http://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee

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 sample:
  1. System.Net.Http: The main NuGet package providing the basic HttpClient and related classes
  2. System.Net.Http.Formatting: Adds support for serialization, deserialization as well as for many additional features building on top of System.Net.Http
  3. System.Json: Adds support for JsonVaue which is a mechanism for reading and manipulating JSON documents
In case you haven’t played with HttpClient before, here is a quick overview of how it works:
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:
  1. An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
  2. You can issue as many requests as you like through a single HttpClient instance.
  3. HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance.
  4. You can derive from HttpClient to create specialized clients for particular sites or patterns
  5. HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.

Kicking the Tires

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. 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:
C#
        static void Main(string[] args) 
        { 
            // Create an HttpClient instance 
            HttpClient client = new HttpClient(); 
 
            // Send a request asynchronously continue when complete 
            client.GetAsync(_address).ContinueWith( 
                (requestTask) => 
                { 
                    // Get HTTP response from completed task. 
                    HttpResponseMessage response = requestTask.Result; 
 
                    // Check that response was successful or throw exception 
                    response.EnsureSuccessStatusCode(); 
 
                    // Read response asynchronously as JsonValue and write out top facts for each country 
                    response.Content.ReadAsAsync<JsonArray>().ContinueWith( 
                        (readTask) => 
                        { 
                            Console.WriteLine("First 50 countries listed by The World Bank..."); 
                            foreach (var country in readTask.Result[1]) 
                            { 
                                Console.WriteLine("   {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}", 
                                    country.Value["name"], 
                                    country.Value["iso2Code"], 
                                    country.Value["capitalCity"], 
                                    country.Value["latitude"], 
                                    country.Value["longitude"]); 
                            } 
                        }); 
                }); 
 
            Console.WriteLine("Hit ENTER to exit..."); 
            Console.ReadLine(); 
        }
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.

More Information

  1. Please see the blog HttpClient is Here! for detailed information about this sample
  2. See ASP.NET Web API for more information on the project

Комментариев нет:

Отправить комментарий