通过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());
    }
}
相关推荐
dreams_dream6 分钟前
vue中axios与fetch比较
前端·javascript·vue.js
lew-yu21 分钟前
【已解决】Linux中程序脚本可以手动执行成功,但加在rc.local中不能开机自启
linux·服务器
ajassi200023 分钟前
linux C 语言开发 (四) linux系统常用命令
linux·运维·服务器
梦鱼27 分钟前
Vue 项目图标一把梭:Iconify 自用小记(含 TS/JS 双版本组件)
前端·javascript·vue.js
best66628 分钟前
Flex 与 Grid 的 order 参数:布局界的 "插队神器"
前端
小噔小咚什么东东28 分钟前
看到了很多次WebRTC,但是你真的需要它吗?
前端·webrtc
猫七先生29 分钟前
微信小程序一键登录可行性方案
前端·微信小程序
维他AD钙29 分钟前
前端开发 8 个非常实用小技巧:高效解决日常开发痛点
前端
光影少年34 分钟前
webpack和vite优化方案都有哪些
前端·webpack·node.js
给月亮点灯|35 分钟前
Vue基础知识-脚手架开发-初始化目录解析
前端·javascript·vue.js