HttpClient获取图片并保存到本地
1. FileDownLoad.cs
本次测试使用HttpClient从网站下载图片并保存到本地,在FileDownLoad类中提供DownLoadInBackGround接口,供外部调用,封装具体的下载操作。
using System; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace CSProject { public delegate void DownLoadMethodInvoker(bool ret, string URL, string fullfilename); //处理下载回调,后期可以作为下载接口的外部参数,提供给外部调用者处理下载后的操作 public class FileDownLoad { private static string PATH = "E:/VSWorkspace/CSharp/CSProject/CSProject/Data/Images/";//本地地址 private static FileDownLoad instance = null; private static HttpClient httpClient = null; private static HttpClientHandler httpClientHandler = null; public static FileDownLoad Instance { get { if(instance == null) { instance = new FileDownLoad(); //设置相关的参数 httpClientHandler = new HttpClientHandler() { MaxConnectionsPerServer = 10, MaxAutomaticRedirections = 10, }; httpClient = new HttpClient(httpClientHandler) { Timeout = TimeSpan.FromSeconds(10), }; } return instance; } } //下载接口,供外部调用 public void DownLoadInBackGround(string URL, string filename) { if (!string.IsNullOrEmpty(URL)) { Task.Factory.StartNew(async () => await DownLoadAsync(URL, filename, DownLoadCallBack)); } } //Callback也可以设置为DownLoadInBackGround接口的参数,直接使用调用者的Callback private void DownLoadCallBack(bool ret, string URL, string fullfilename) { if (!ret) { Console.WriteLine("Download result = " + ret); Console.WriteLine($"URL = {URL},LocalPath = {fullfilename}"); return; } } private async Task DownLoadAsync(string URL, string filename, DownLoadMethodInvoker callback) { Console.WriteLine("URL = " + URL); try { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, URL)) { using (HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { long? contentLength = 0; if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 600) { Console.WriteLine("Error statuscode = " + response.StatusCode); return; } try { response.EnsureSuccessStatusCode(); contentLength = response.Content.Headers.ContentLength; Console.WriteLine("ContentLength = " + response?.Content?.Headers?.ContentLength); int bufferSize = contentLength > 0 ? (int)contentLength : 1024 * 100;//默认100KB以下 byte[] buffer = new byte[bufferSize + 1024 * 2];//添加2KB冗余空间 buffer = await response.Content.ReadAsByteArrayAsync(); //将读取到的内容写进本地文件 using (FileStream fileStream = new FileStream(PATH + filename, FileMode.Create)) { Console.WriteLine("Read file complete, filesize = " + bufferSize); fileStream.Write(buffer, 0, bufferSize); Console.WriteLine("Write End, URL = " + URL); } callback?.Invoke(true, URL, PATH + filename); } catch (Exception ex) { Console.WriteLine("exception = " + ex.Message); callback?.Invoke(false, URL, PATH + filename); } } } } catch (Exception ex) { Console.WriteLine("Exception = " + ex.Message); callback?.Invoke(false, URL, PATH + filename); } } } }
2. FileDownLoadTC.cs
编写测试类FileDownLoadTC,提供测试方法,并调用之前实现的下载接口
using System; namespace CSProject { public class FileDownLoadTC { private static FileDownLoadTC instance; public static FileDownLoadTC Instance { get { if(instance == null) { instance = new FileDownLoadTC(); } return instance; } } public void Test() { //图片位置:https://img.infinitynewtab.com/wallpaper/ for (int i = 1; i <= 300; i++) { string URL = "https://img.infinitynewtab.com/wallpaper/" + i + ".jpg"; FileDownLoad.Instance.DownLoadInBackGround(URL, i.ToString("D3") + ".jpg"); } } } }
3. Program.cs
调用测试方法
using System; namespace CSProject { internal class Program { static void Main(string[] args) { FileDownLoadTC.Instance.Test(); Console.ReadLine(); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章