通过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());
    }
}
相关推荐
香蕉可乐荷包蛋8 分钟前
vue对axios的封装和使用
前端·javascript·vue.js·axios
娃哈哈哈哈呀12 分钟前
html - <mark>标签
前端·html
QQ_hoverer12 分钟前
前端使用 preview 插件预览docx文件
前端·javascript·layui·jquery
陈随易14 分钟前
Lodash 杀手来了!es-toolkit v1.39.0 已完全兼容4年未更新的 Lodash
前端·后端·程序员
Thomas游戏开发20 分钟前
Unity3D TextMeshPro终极使用指南
前端·unity3d·游戏开发
potender22 分钟前
前端基础学习html+css+js
前端·css·学习·html·js
Hilaku30 分钟前
你以为的 Tailwind 并不高效,看看这些使用误区
前端·css·前端框架
帅夫帅夫32 分钟前
Vibe Coding从零开始教你打造一个WebLLM页面
前端·人工智能
Vonalien33 分钟前
Trae 深度体验:从怀疑到真香,AI 如何重塑我的开发流?
前端
刘白Live34 分钟前
【html】localStorage设置和获取局部存储的值
前端