HttpClient vs Webclient vs HttpWebRequest Options

codeling 1247 - 5334
@2020-01-06 15:17:37

System.Net.WebRequest is an abstract class, System.Net.HttpWebRequest and System.Net.FileWebRequest will inherit the WebRequest.

The System.Net.WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.

The System.Net.Http.HttpClient class is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. 

The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol. However, WebClient class had some limitations. The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient. Microsoft doesn't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.

 

Web­Client

 

Http­Client

 Avail­able in older ver­sion of .NET  .NET 4.5 or later version. Cre­ated to sup­port the grow­ing need of the Web API REST calls
 WinRT appli­ca­tions can­not use WebClient  Http­Client can be used with WinRT
 Pro­vides progress report­ing for downloads.  No progress report­ing for downloads.
 Does not reuse resolved DNS, configured-cookies.  Can reuse resolved DNS, cookie con­fig­u­ra­tion, and other authentication.
 You need to new up a Web­Client to make the con­cur­rent request.  Sin­gle Http­Client can make con­cur­rent requests.
 Thin layer over WebRe­quest and WebResponse  Thin layer over Http­We­bRe­quest and HttpWebResponse
 Mock­ing and test­ing Web­Client is difficult  Mock­ing and test­ing Http­Client is easy
 Sup­ports FTP.  No sup­port for FTP.
 Both syn­chro­nous and Asyn­chro­nous meth­ods are avail­able for IO bound requests.  All IO bound meth­ods in HTTP­Client are asynchronous.

 

 

 

codeling 1247 - 5334
@2020-01-06 15:32:11

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

Below is an example using HttpClient correctly.

public class GoodController : ApiController
{
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}
Users browsing this topic
Guest