通过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());
    }
}
相关推荐
软件黑马王子16 分钟前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
丁卯40440 分钟前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo41 分钟前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
晴空万里藏片云1 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一1 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球1 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7231 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
人间打气筒(Ada)2 小时前
MySQL主从架构
服务器·数据库·mysql
落笔画忧愁e3 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
小冷爱学习!3 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为