通过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());
    }
}
相关推荐
Heo几秒前
关于XSS和CSRF,面试官更喜欢这样的回答!
前端·javascript·面试
7***A44322 分钟前
Vue自然语言处理应用
前端·vue.js·自然语言处理
2501_9219392623 分钟前
11.25Nginx服务器和Wordpress服务器
运维·服务器·nginx
高阳言编程40 分钟前
vue2 + node + express + MySQL 5.7 的购物系统
前端
y***54881 小时前
React依赖
前端·react.js·前端框架
2***B4491 小时前
React测试
前端·react.js·前端框架
wanhengidc1 小时前
云手机中分布式存储的功能
运维·服务器·分布式·游戏·智能手机·云计算
5***o5001 小时前
React自动化测试
前端·react.js·前端框架
T***u3331 小时前
React部署
前端·react.js·前端框架
p***32351 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互