使用WebClient还是HttpClient下载文件? [英] Download file with WebClient or HttpClient?

查看:282
本文介绍了使用WebClient还是HttpClient下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL下载文件,并且必须在WebClient和HttpClient之间进行选择。我已引用这篇文章以及互联网上的其他几篇文章。到处建议使用HttpClient,因为它具有强大的异步支持和其他.Net 4.5特权。但是我仍然没有完全相信,需要更多的投入。

I am trying to download file from a URL and I have to choose between WebClient and HttpClient. I have referenced this article and several other articles on the internet. Everywhere, it is suggested to go for HttpClient due to its great async support and other .Net 4.5 privileges. But I am still not totally convinced and need more inputs.

我正在使用以下代码从Internet下载文件:

I am using below code to download file from internet:

WebClient:

WebClient client = new WebClient();
client.DownloadFile(downloadUrl, filePath);

HttpClient:

using (HttpClient client = new HttpClient())
{        
    using (HttpResponseMessage response = await client.GetAsync(url))
    using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
    {
    }
}

从我的角度来看,我只能看到使用WebClient的一个缺点,那就是非异步调用,阻塞了调用线程。但是,如果我不担心线程阻塞或使用 client.DownloadFileAsync()来利用异步支持怎么办?

From my perspective, I can see only one disadvantage in using WebClient, that would be the non async call, blocking the calling thread. But what if I am not worried about the blocking of thread or use client.DownloadFileAsync() to leverage the async support?

另一方面,如果我使用HttpClient,不是将文件的每个字节加载到内存中,然后将其写入本地文件吗?如果文件太大,内存开销会不会很昂贵?如果我们使用WebClient,则可以避免这种情况,因为它将直接写入本地文件,而不消耗系统内存。

On the other hand, if I use HttpClient, ain't I loading every single byte of a file into memory and then writing it to a local file? If the file size is too large, won't memory overhead be expensive? Which could be avoided if we use WebClient, since it will directly write to local file and not consume system memory.

因此,如果性能是我的首要任务,则应采用哪种方法我用下载吗?如果上述假设是错误的,我想澄清一下,并且我也愿意接受其他方法。

So, if performance is my utter priority, which approach should I use for download? I would like to be clarified if my above assumption is wrong, and I am open to alternate approach as well.

推荐答案

我的方法。

如果您正在调用WebApi来获取文件,则可以从控制器方法中使用HttpClient GET请求并使用FileStreamResult返回类型返回文件流。

If you are calling a WebApi to get a file, then from a controller method you can use HttpClient GET request and return file stream using FileStreamResult return type.

public async Task<ActionResult> GetAttachment(int FileID)
{
    UriBuilder uriBuilder = new UriBuilder();
    uriBuilder.Scheme = "https";
    uriBuilder.Host = "api.example.com";

    var Path = "/files/download";
    uriBuilder.Path = Path;
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(uriBuilder.ToString());
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("authorization", access_token); //if any
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await client.GetAsync(uriBuilder.ToString());

            if (response.IsSuccessStatusCode)
            {
                System.Net.Http.HttpContent content = response.Content;
                var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream
                return File(contentStream, content_type, filename);
            }
            else
            {
                throw new FileNotFoundException();
            }
    }
}

这篇关于使用WebClient还是HttpClient下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆