通过http地址下载文件

1.HttpWebResponse方法

cs 复制代码
public void GetPostContent(string url, string localSavePath)
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
        myRequest.Method = "GET";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.Proxy = null;
        

        // Get response
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        Stream responseStream = myResponse.GetResponseStream();
        Stream stream = new FileStream(localSavePath, FileMode.Create);

        byte[] bArr = new byte[1024];
        int size = responseStream.Read(bArr, 0, (int)bArr.Length);
        while (size > 0)
        {
            stream.Write(bArr, 0, size);
            size = responseStream.Read(bArr, 0, (int)bArr.Length);
        }
        stream.Close();
        responseStream.Close();
    }
    catch (System.Exception ex)
    {
        throw ex;
    }
}

2.HttpClient方法

cs 复制代码
public static async void  DownloadFile(string url, string filePath)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode(); // 确保HTTP成功状态值  

            // 读取响应内容并保存到文件  
            using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
                   fileStream = File.Create(filePath))
            {
                await contentStream.CopyToAsync(fileStream);
            }

            Console.WriteLine("文件下载完成。");
        }
    }
    catch (HttpRequestException e)
    {
        MessageBox.Show(e.ToString());
    }
}
相关推荐
小毛驴8504 分钟前
创建 Vue 项目的 4 种主流方式
前端·javascript·vue.js
誰能久伴不乏33 分钟前
Linux如何执行系统调用及高效执行系统调用:深入浅出的解析
java·服务器·前端
涔溪2 小时前
响应式前端设计:CSS 自适应布局与字体大小的最佳实践
前端·css
今禾2 小时前
前端开发中的Mock技术:深入理解vite-plugin-mock
前端·react.js·vite
你这个年龄怎么睡得着的2 小时前
Babel AST 魔法:Vite 插件如何让你的 try...catch 不再“裸奔”?
前端·javascript·vite
我想说一句2 小时前
掘金移动端React开发实践:从布局到样式优化的完整指南
前端·react.js·前端框架
jqq6662 小时前
Vue3脚手架实现(九、渲染typescript配置)
前端
★YUI★2 小时前
学习游戏制作记录(剑投掷技能)7.26
学习·游戏·unity·c#
码间舞2 小时前
Zustand 与 useSyncExternalStore:现代 React 状态管理的极简之道
前端·react.js
Dream耀2 小时前
提升React移动端开发效率:Vant组件库
前端·javascript·前端框架