通过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());
    }
}
相关推荐
寒山李白23 分钟前
VuePress搭建文档网站/个人博客(详细配置)主题配置-侧边栏配置
前端·vue.js·vue·博客·vuepress·网站
weipt40 分钟前
git服务器私有化部署产品
运维·服务器·git
二十雨辰41 分钟前
[uni-app]小兔鲜-01项目起步
前端·javascript·vue.js·uni-app
kkkAloha1 小时前
面经 | JS
开发语言·前端·javascript
忒可君1 小时前
Qt/C++开发经验
数据库·c++·qt·学习·c#
芥子沫1 小时前
Safari-常用快捷键(IPadOS版本)
前端·safari
wgc891782 小时前
Zabbix短信告警示例
前端·chrome·zabbix
forestqq2 小时前
配置docker的proxy指向
运维·服务器·容器
逝缘~2 小时前
uni-icons自定义图标详细步骤及踩坑经历
前端·javascript·css·vue.js·uni-app·html
wanhengwangluo2 小时前
高防服务器如何抵御网络攻击?
服务器·网络攻击·高防服务器