通过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());
    }
}
相关推荐
程序员小崔日记4 小时前
20块钱注册一年 .COM 域名!Spaceship 最新优惠教程,支付宝即可付款(附优惠码)
服务器·腾讯云·域名
实心儿儿5 小时前
Linux —— 进程间关系和守护进程
linux·运维·服务器
林浅不想努力5 小时前
LVS知识点总结
服务器·云原生·lvs
石小石Orz5 小时前
我发现了开发者AI产品营收的新方向
前端·虚拟现实
老马识途2.06 小时前
关于跨域问题的总结
java·前端
Dawn-bit6 小时前
Linux磁盘管理详解
linux·运维·服务器·计算机网络·云计算
别惊醒渔人7 小时前
Vue3 Diff 优化:最长递增子序列 LIS
前端·javascript·vue.js
颜酱8 小时前
07 | 把字段与指标同步到 Qdrant(生成阶段)
前端·人工智能·后端
用户059540174468 小时前
把AI长期记忆测试从手动验证换成pytest,2天揪出11个隐藏Bug
前端·css
lichenyang4539 小时前
从 Vite 空项目到 AIGC 图片工作台:我如何打通生图、任务轮询、生成库与 Canvas 动态特效
前端·人工智能