net core HttpClient

序列化和反序列化来自网络的 JSON 有效负载是常见的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace HttpClientExtensionMethods
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string Email { get; set; }
}

public class Program
{
public static async Task Main()
{
using HttpClient client = new()
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com")
};

// Get the user information.
User user = await client.GetFromJsonAsync<User>("users/1");
Console.WriteLine($"Id: {user.Id}");
Console.WriteLine($"Name: {user.Name}");
Console.WriteLine($"Username: {user.Username}");
Console.WriteLine($"Email: {user.Email}");

// Post a new user.
HttpResponseMessage response = await client.PostAsJsonAsync("users", user);
Console.WriteLine(
$"{(response.IsSuccessStatusCode ? "Success" : "Error")} - {response.StatusCode}");
}
}
}

// Produces output like the following example but with different names:
//
//Id: 1
//Name: Tyler King
//Username: Tyler
//Email: Tyler @contoso.com
//Success - Created