https://www.bilibili.com/video/BV1u94y1x7RQ/
HttpClient 是实现了 Disposed 接口的,所以按理来说是这么使用的:
using var client = new HttpClient();
如果每次发送请求都要new一个HttpClient,那么会占用不同的端口,且不会再短时间内释放掉,所以,会出现问题,也就不推荐这么使用了;
我们一般使用官方推荐的 HttpClient工厂方式;
安装
Microsoft.Extensions.Http
Microsoft.Extensions.DependencyInjection
using Microsoft.Extensions.DependencyInjection;
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient(); // 全局的client
serviceCollection.AddHttpClient("testClient", (client) => { // 加了一个名字
client.BaseAddress = nwe Uri("https://www.baidu.com");
client.DefaultRequestHeaders.Add("aa", "bbbbbbbb");
});
serviceCollection.AddHttpClinet<Test2Service>((client)=>{
client.DefaultRequestHeaders.Add("bb", "cccccccc");
});
serviceCollection.AddSingleton<TestService>();
var service = serviceCollection.BuildServiceProvider();
var httpClientFactory = service.GetRequiredService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient();
var str = client.GetStringAsync("https://www.so.com");
Console.WriteLine(str);
// --------------
var testService = service.GetRequiredService<TestService>();
Console.WriteLine(await testService.GetString());
// --------------
var test2Service = service.GetRequiredService<Test2Service>();
Console.WriteLine(await test2Service.GetString());
新建一个 TestService.cs 文件:
namespace HttpclientTest
{
internal class TestService{
private HttpClient _client;
public TestService(IHttpClientFactory clientFactory){
_client = clientFactory.CreateClient("testClient");
}
public async Task<string> GetString(){
return await _client.GetStringAsync("/api/ccccc");
}
}
}
新建一个 Test2Service.cs 文件
namespace HttpclientTest
{
internal class Test2Service{
private HttpClient _client;
public Test2Service(HttpClient httpClient){
_client = httpClient;
}
public async Task<string> GetString(){
return await _client.GetStringAsync("/api/ccccc");
}
}
}
未完
|