通过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());
    }
}
相关推荐
姓王者1 分钟前
Astro 6 推出啦
前端
大傻^2 分钟前
【OpenClaw -01】OpenClaw 安装部署指南:npm、Docker 与源码三种模式详解
前端·docker·npm
用户4445543654262 分钟前
Android Toast消息受到Rom的影响
前端
kyriewen2 分钟前
我敢打赌,你还不知道 display 还有这些骚操作!
前端·css·html
格林威3 分钟前
工业相机图像高速存储(C#版):先存内存,后批量转存方法,附海康相机实战代码!
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·海康相机
葡萄城技术团队3 分钟前
解锁 SpreadJS 扩展能力:ECharts 集成与自定义渲染实战
前端
NEAI_N5 分钟前
离网设备的加密解密方案
linux·服务器·网络
来一颗砂糖橘5 分钟前
CSS 清除浮动深度解析:从 clear: both 到现代布局方案
前端·css·clearboth·清除浮动
南宫码农7 分钟前
Node.js和npm本地安装详细教程(全系统适配)
前端·npm·node.js
萝卜白菜。8 分钟前
annotation扫描引起的StackOverflowError问题
linux·运维·服务器