通过http地址下载文件

时间:2024-09-29 15:55:16

1.HttpWebResponse方法

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方法

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());
    }
}