HttpClient vs HttpWebRequest
Solution 1:
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
- An HttpClient instance is the place to configure extensions, set default headers, cancel outstanding requests and more.
- You can issue as many requests as you like through a single HttpClient instance.
- HttpClients are not tied to particular HTTP server or host; you can submit any HTTP request using the same HttpClient instance.
- You can derive from HttpClient to create specialized clients for particular sites or patterns
- HttpClient uses the new Task-oriented pattern for handling asynchronous requests making it dramatically easier to manage and coordinate multiple outstanding requests.
Solution 2:
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
Solution 3:
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 arguably be a long lived object (E.g. the lifetime of the application).
[edit - added context]
Disposing the instance also closes the connection but leaves the socket in a waiting state for a set duration. For each execution of this code, the os will attempt to create a new socket connection, and since there is a limit to how quickly this can be completed, performance/reliability issues can arise.
Reusing the same HttpClient instance means better reuse of open sockets and more efficient use of system resources.
More info here.