HttpClient vs HttpWebRequest

2019-01-10 20:35发布

I have a large file which I have to send to a web api client...The data is multi part. The issue is , if the file is sent over http web request, then it is uploaded quickly on the webapi. For this request, file contents are written over the request stream directly.

Where as if the same file is sent over Httpclient (.net 4.5), the upload is slow when compared to http web request. I am using multipartformdatacontent in Httpclient post async.

So, for large files, do we have to use only web request? or is there any settings on Httpclient that makes the upload faster?

3条回答
唯我独甜
2楼-- · 2019-01-10 20:55

HttpClient is more like a head-less browser. It a powerfull and ideal tool if you are going to be creating many http request. For example you can set default headers and stuff. Here are the top 5 ways it differs from an HttpWebRequest which is taken from here

  1. An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
  2. You can issue as many requests as you like through a single HttpClient instance.
  3. HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance.
  4. You can derive from HttpClient to create specialized clients for particular sites or patterns
  5. HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.
查看更多
Melony?
3楼-- · 2019-01-10 20:57

Perhaps you were instantiating HttpClient in a using block which could explain performance issues. E.g.

  using (var httpClient = new HttpClient() )
  {
      var result = await httpClient.GetAsync("http://example.com");
      Console.WriteLine(result.StatusCode);
  }

Here the instance of HttpClient is being disposed immediately after the request whereas it should be a long lived object (E.g. the lifetime of the application).

More info here.

查看更多
做自己的国王
4楼-- · 2019-01-10 20:59

I was using FileStreamContent with httpclient...But when I used ByteArrayContent, it worked fine.

I am not sure how and why this made the difference, but sending bytes over the stream is a better way rather than sending the stream

查看更多
登录 后发表回答