MSDN给出的HttpClient使用示例

时间:2022-03-01 13:50:12
 1 using System;
2 using System.Json;
3 using System.Net.Http;
4
5 namespace WorldBankSample
6 {
7 /// <summary>
8 /// Sample download list of countries from the World Bank Data sources at http://data.worldbank.org/
9 /// </summary>
10 class Program
11 {
12 static string _address = "http://api.worldbank.org/countries?format=json";
13
14 static void Main(string[] args)
15 {
16 // Create an HttpClient instance
17 HttpClient client = new HttpClient();
18
19 // Send a request asynchronously continue when complete
20 client.GetAsync(_address).ContinueWith(
21 (requestTask) =>
22 {
23 // Get HTTP response from completed task.
24 HttpResponseMessage response = requestTask.Result;
25
26 // Check that response was successful or throw exception
27 response.EnsureSuccessStatusCode();
28
29 // Read response asynchronously as JsonValue and write out top facts for each country
30 response.Content.ReadAsAsync<JsonArray>().ContinueWith(
31 (readTask) =>
32 {
33 Console.WriteLine("First 50 countries listed by The World Bank...");
34 foreach (var country in readTask.Result[1])
35 {
36 Console.WriteLine(" {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}",
37 country.Value["name"],
38 country.Value["iso2Code"],
39 country.Value["capitalCity"],
40 country.Value["latitude"],
41 country.Value["longitude"]);
42 }
43 });
44 });
45
46 Console.WriteLine("Hit ENTER to exit...");
47 Console.ReadLine();
48 }
49 }
50 }

其中涉及了异步的操作,可以在以后的工作中加以借鉴。

注释:

ContinueWith是Task对象的一个方法。ContinueWith接受一个参数,这个参数是Action<T>,而Action<T>是委托,指向一个有一个参数、无返回值的方法。当然参数的类型是由T给出的。具体的来说,这里ContinueWith的参数类型是Action<Task>,且这个Task类型的参数是自动传递的。例子里给出了两个匿名方法来实现委托,都无返回值,参数是Task类型,参数由ContinueWith前面方法返回的Task自动传入。