创建实例

var httpClient = new HttpClient()

使用httpClientFactory

var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient(); // asp.net core 中只需要在startup.cs这个添加这个,然后在其他地方注入即可
var serviceProvider = serviceCollection.BuildServiceProvider();
IHttpClientFactory httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

var httpClient = httpClientFactory.CreateClient();

POST JSON

var httpClient = httpClientFactory.CreateClient();
httpClient.Timeout = TimeSpan.FromSeconds(60 * 15);


// 创建HttpContent对象
var args = new { year = 2024 };
var json = Newtonsoft.Json.JsonConvert.SerializeObject(args );
HttpContent content = new StringContent(json , Encoding.UTF8);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

var response = httpClient.PostAsync(apiUrl, content).Result;
response.EnsureSuccessStatusCode();
// 读取响应内容(如果需要)
string responseData = response.Content.ReadAsStringAsync().Result;