当前位置: 首页> 游戏> 游戏 > wpf中使用 HttpClientFactory创建HttpClient并下载文件

wpf中使用 HttpClientFactory创建HttpClient并下载文件

时间:2025/7/9 15:08:46来源:https://blog.csdn.net/daqinzl/article/details/142286701 浏览次数:0次

一,利用HttpClient下载文件的方法
public static async Task<bool> HttpDownloadFile(string downloadUrl, string localPath, log4net.ILog log)
        {
            bool bFlagDownloadFile = false;
            //log.Debug("HttpDownloadFile--准备以HTTP的方式下载文件,url:[" + downloadUrl + "]本地文件:【" + localPath + "】");
                        
            try
            {
                var client = MainWindow.getHttpClient(); //定义见下面的“使用httpclientfactory”
                //var client = new HttpClient();
                //var response = client.GetAsync(downloadUrl).Result;
                //if (response.IsSuccessStatusCode) // 确保HTTP响应状态码表示成功
                //{
                //    using (var fs = new FileStream(localPath, FileMode.Create))
                //    {
                //        await response.Content.CopyToAsync(fs);                        
                //        bFlagDownloadFile = true;
                //        log.Debug("HttpDownloadFile--以HTTP的方式下载文件,本地文件:【" + localPath + "】成功!");
                //    }
                //}

                using (var response = await client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();

                    using (var fileStream = new FileStream(localPath, FileMode.Create))
                    {
                        using (var httpStream = await response.Content.ReadAsStreamAsync())
                        {
                            await httpStream.CopyToAsync(fileStream);
                            bFlagDownloadFile = true;
                            log.Debug("HttpDownloadFile--以HTTP的方式下载文件,本地文件:【" + localPath + "】成功!");
                        }
                    }
                    
                }

            }
            catch (Exception ex)
            {
                log.Error("HttpDownloadFile--以HTTP的方式下载文件,本地文件:【" + localPath + "】时发生错误!异常消息:" + ex.Message, ex);
                bFlagDownloadFile = false;
            }

            return bFlagDownloadFile;
        }


二、WPF使用httpclientfactory,步骤如下:

1,安装必要的NuGet包:

Microsoft.Extensions.DependencyInjection 和 Microsoft.Extensions.Http

2,配置依赖注入。

2.1,启动类App设置

using System;
using Microsoft.Extensions.DependencyInjection;

public partial class App : Application
{

    public ServiceCollection services;

    //在启动类App的启动方法
    private void AppStartup(object sender, StartupEventArgs e)
    {

        services = new ServiceCollection();
        services.AddHttpClient();
        services.AddTransient(typeof(MainWindow));
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        MainWindow mainWindow = serviceProvider.GetRequiredService<MainWindow>();
    
    }

}

2.2,主窗口类MainWindow设置

using System.Net.Http;

public partial class MainWindow : Window
{
    private static IHttpClientFactory _httpClientFactory;
    
    public MainWindow()
    {            
        //... 可以有个缺省的构造方法           
    }

    public MainWindow(IHttpClientFactory httpClientFactory)
    {            
        _httpClientFactory = httpClientFactory;            
    }

    public static HttpClient getHttpClient()
    {
        var client = _httpClientFactory.CreateClient();
        return client;
    }
}

3,使用
var client = MainWindow.getHttpClient();


 

关键字:wpf中使用 HttpClientFactory创建HttpClient并下载文件

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: