通过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());
    }
}
相关推荐
GIS之路6 分钟前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
haimin037121 分钟前
linux设置CPU固定频率
linux·运维·服务器
朴shu1 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端
一条咸鱼¥¥¥1 小时前
【运维经验】服务器磁盘做镜像的方法
运维·服务器·windows·经验分享
渣渣盟1 小时前
NFS服务器配置全攻略:从入门到精通
linux·运维·服务器
一只旭宝1 小时前
Linux专题九:I/O复用(水平以及边缘触发放到libevent库那一专题细讲)
linux·运维·服务器
缘如风1 小时前
Linux上sunrpc 111端口关闭
linux·服务器
I · T · LUCKYBOOM2 小时前
iptables防火墙
linux·运维·服务器·网络·安全
MediaTea2 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
字节跳动开源2 小时前
Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁
前端·人工智能·客户端