一,利用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();