通过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());
    }
}
相关推荐
江湖行骗老中医2 分钟前
Pinia 是 Vue 的专属状态管理库
前端·javascript·vue.js
用户69371750013843 分钟前
Android 开发,别只钻技术一亩三分地,也该学点“广度”了
android·前端·后端
郑鱼咚4 分钟前
别再神化Spec了,它可能只是AI Coding的临时补丁
前端
张元清8 分钟前
React 鼠标追踪与交互效果实战
前端·javascript·面试
MinterFusion8 分钟前
HTML DOM元素的定位问题
前端·css·html
航Hang*9 分钟前
第2章:进阶Linux系统——第4节:配置与管理NFS服务器
linux·运维·服务器·笔记·学习·vmware
落魄江湖行21 分钟前
入门篇六 Nuxt4错误处理:给应用装个安全气囊
前端·typescript·nuxt4
薛定猫AI25 分钟前
【技术干货】用 design.md 驯服 AI 生成前端:从 Awesome Design 到工程化落地实践
前端·人工智能
kyriewen28 分钟前
你的JS代码总在半夜崩溃?TypeScript来“上保险”了
前端·javascript·typescript
wjp@00137 分钟前
SQL server导出导入数据
运维·服务器·数据库