C# .NET Framework4.61以上使用IHttpClientFactory

1.首先添加Microsoft.Extensions.Http和Microsoft.Extensions.DependencyInjection依赖项

2.如果请求地址是https,则加上System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

3.请求接口

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<System.Net.Http.IHttpClientFactory>();
var client = httpClientFactory.CreateClient();
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "https://www.xxxxx.cn:10002/api/app/client-message/is-warning"));
var content = await response.Content.ReadAsStringAsync();

posted @ 2021-07-08 10:03  北极星下落不明  阅读(912)  评论(0)    收藏  举报