通过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());
    }
}
相关推荐
weixin_462446234 分钟前
Python用Flask后端解析Excel图表,Vue3+ECharts前端动态还原(附全套代码)
前端·python·flask·echats
满栀5858 分钟前
jQuery 递归渲染多级树形菜单
前端·javascript·jquery
闲蛋小超人笑嘻嘻11 分钟前
Flexbox 属性总结
前端·css
TOPGUS14 分钟前
谷歌将移除部分搜索功能:面对AI时代的一次功能精简策略
前端·人工智能·搜索引擎·aigc·seo·数字营销
Learn Forever15 分钟前
【Linux】iptables常用指令
linux·运维·服务器
运筹vivo@23 分钟前
攻防世界: ics-05
前端·web安全·php
Saniffer_SH26 分钟前
【高清视频】笔记本电脑出现蓝屏、死机、慢、不稳定是这样连接分析M.2 SSD的
运维·服务器·网络·人工智能·驱动开发·嵌入式硬件·fpga开发
不思念一个荒废的名字26 分钟前
【黑马JavaWeb+AI知识梳理】Web前端开发 - Vue3 / ElementPlus
前端
宴之敖者、29 分钟前
Linux——编译器-gcc/g++
linux·运维·服务器
月明长歌29 分钟前
Selenium中隐式等待(Implicit Wait)和显式等待(Explicit Wait)的区别
前端·javascript·selenium