通过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());
    }
}
相关推荐
美酒没故事°5 分钟前
npm源管理器:nrm
前端·npm·npm源
用户22152044278005 分钟前
vue3组件间的通讯方式
前端·vue.js
三十_A23 分钟前
【实录】使用 patch-package 修复第三方 npm 包中的 Bug
前端·npm·bug
下位子31 分钟前
『AI 编程』用 Claude Code 从零到一开发全栈减脂追踪应用
前端·ai编程·claude
tyro曹仓舒31 分钟前
Vue单文件组件到底需不需要写name
前端·vue.js
用户479492835691532 分钟前
面试官:讲讲2FA 双因素认证原理
前端·后端·安全
乐影32 分钟前
TS 模板字符串类型:从基础到进阶的类型编程魔法
前端·typescript
龙在天33 分钟前
CSS 属性值的计算与过程
前端
云鹤_34 分钟前
【Amis源码阅读】组件注册方法远比预想的多!
前端·低代码
xinfei36 分钟前
ES6 新特性 从 ECMAScript 2015(ES6)到 ECMAScript 2025
前端