0
点赞
收藏
分享

微信扫一扫

.Net C# HttpClient

芭芭蘑菇 2022-02-15 阅读 95

在.Net开发中,经常会有需要处理http请求的需求,以前使用WebRequest获取WebClient来处理,现在官方推荐使用HttpClient来处理Http请求相关操作。

简单使用可以直接创建HttpClient实例(注意释放资源):

HttpClient http = new HttpClient();

如果复用连接时可以推荐使用IHttpClientFactory和封装为具体服务的形式。

参考代码:

internal class HttpClientDemo
    {
        //全局容器
        static IHost host;
        static IHttpClientFactory clientFactory;
        public static async Task DemoMain()
        {
            //向容器添加缓存服务
            host = Host.CreateDefaultBuilder()
                .ConfigureServices(services => {
                    services.AddHttpClient();
                    services.AddHttpClient<IMicrosoftClient, MicrosoftClient>();
                })
                .Build();
            //获取IHttpClientFactory用来管理HttpClient,复用连接
            clientFactory = host.Services.GetService<IHttpClientFactory>();

            //普通用法
            var client = GetHttpClient("https://docs.microsoft.com/zh-cn/");
            var result = await client.GetAsync("/");
            var content = await result.Content.ReadAsStringAsync();
            //Console.WriteLine(content);
            Console.WriteLine("------------------------------");
            var resultStr = await client.GetStringAsync("/");
            //Console.WriteLine(resultStr);
            Console.WriteLine($"{content.Length}--{resultStr.Length}");

            //封装为单独服务后使用
            IMicrosoftClient microsoftClient =host.Services.GetRequiredService<IMicrosoftClient>();
            string microsoftResult= await microsoftClient.GetStr("/");
            Console.WriteLine(microsoftResult.Length);

            HttpClient http = new HttpClient();
        }
        /// <summary>
        /// 初始化指定Url相关HttpClient
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <returns></returns>
        private static HttpClient GetHttpClient(string baseUrl)
        {
            var client = clientFactory.CreateClient();
            client.BaseAddress = new Uri(baseUrl);
            client.Timeout = new TimeSpan(0, 0, 0, 30);
            return client;
        }
    }
    //封装HttpClient注入后使用
    internal class MicrosoftClient: IMicrosoftClient
    {
        private readonly HttpClient httpClient;

        public MicrosoftClient(HttpClient httpClient)
        {
            this.httpClient = httpClient;
            this.httpClient.BaseAddress = new Uri("https://docs.microsoft.com/zh-cn/");
        }

        public async Task<string> GetStr(string url)
        {
            return await httpClient.GetStringAsync(url);
        }
    }

    interface IMicrosoftClient
    {
        Task<string> GetStr(string url);
    }

输出结果:

 

举报

相关推荐

0 条评论