{"id":325,"date":"2020-10-24T12:42:00","date_gmt":"2020-10-24T07:12:00","guid":{"rendered":"http:\/\/sumitjangid.com\/?p=325"},"modified":"2020-10-24T12:44:17","modified_gmt":"2020-10-24T07:14:17","slug":"consuming-api-and-webclient-vs-httpclient-vs-httpwebrequest","status":"publish","type":"post","link":"http:\/\/sumitjangid.com\/index.php\/2020\/10\/24\/consuming-api-and-webclient-vs-httpclient-vs-httpwebrequest\/","title":{"rendered":"Consuming API and WebClient vs. HttpClient vs. HttpWebRequest"},"content":{"rendered":"\n<p>In a nutshell, WebRequest\u2014in its HTTP-specific implementation, HttpWebRequest\u2014represents the original way to consume HTTP requests in .NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .NET Framework 4.5.<\/p>\n\n\n\n<h2>System.Net.WebRequest<\/h2>\n\n\n\n<p>The System.Net.WebRequest class is an abstract class. Thus you will need to create a HttpWebRequest or FileWebRequest to consume HTTP requests using this class. The following code snippet shows how you can work with WebRequest.<\/p>\n\n\n\n<p><strong>WebRequest<\/strong> webRequest = <strong>WebRequest<\/strong>.<strong>Create<\/strong>(uri); webRequest.<strong>Credentials<\/strong> = <strong>CredentialCache<\/strong>.<strong>DefaultCredentials<\/strong>; webRequest.<strong>Method<\/strong> =&#8221;GET&#8221;; <strong>HttpWebResponse<\/strong> webResponse = (<strong>HttpWebResponse<\/strong>)webRequest.<strong>GetResponse<\/strong>(); <\/p>\n\n\n\n<h2><strong>System<\/strong>.<strong>Net<\/strong>.<strong>HttpWebRequest<\/strong><\/h2>\n\n\n\n<p>WebRequest was the first class provided in the .NET Framework to consume HTTP requests. It gives you a lot of flexibility in handling each and every aspect of the request and response objects, without blocking the user interface thread. You can use this class to access and work with headers, cookies, protocols, and timeouts when working with HTTP. The following code snippet illustrates how HttpWebRequest can be used.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>HttpWebRequest<\/strong> http = <strong>HttpWebRequest<\/strong>)<strong>WebRequest<\/strong>.<strong>Create<\/strong>(\u201chttp:<em>\/\/localhost:8900\/api\/default\u201d);<\/em>\n<strong>WebResponse<\/strong> response = http.<strong>GetResponse<\/strong>();\n<strong>MemoryStream<\/strong> memoryStream = response.<strong>GetResponseStream<\/strong>();\n<strong>StreamReader<\/strong> streamReader = <strong>new<\/strong> <strong>StreamReader<\/strong>(memoryStream);\n<strong>string<\/strong> data = streamReader.<strong>ReadToEnd<\/strong>();\n<\/pre>\n\n\n\n<h2>System.Net.WebClient<\/h2>\n\n\n\n<p>The System.Net.WebClient class in .NET provides a high-level abstraction on top of HttpWebRequest. WebClient is just a wrapper around HttpWebRequest, so uses HttpWebRequest internally. Thus WebClient is a bit slow compared to HttpWebRequest, but requires you to write much less code. You can use WebClient for simple ways to connect to and work with HTTP services. It is generally a better choice than HttpWebRequest unless you need to leverage the additional features that HttpWebRequest provides. The following code snippet shows how you can work with WebClient.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>string<\/strong> data = <strong>null<\/strong>;<br><strong>using<\/strong> (<strong>var<\/strong> webClient = <strong>new<\/strong> <strong>WebClient<\/strong>())<br>{<br>&nbsp; &nbsp; data = webClient.<strong>DownloadString<\/strong>(url);<br>}<\/pre>\n\n\n\n<h2>System.Net.Http.HttpClient<\/h2>\n\n\n\n<p>HttpClient was introduced in .NET Framework 4.5. For developers using .NET 4.5 or later, it is the preferred way to consume HTTP requests unless you have a specific reason not to use it. In essence, HttpClient combines the flexibility of HttpWebRequest and the simplicity of WebClient, giving you the best of both the worlds.<\/p>\n\n\n\n<p>The HttpWebRequest class provides a lot of control over the request\/response object. However, you should be aware that HttpClient was never designed to be a replacement for WebClient. You should use HttpWebRequest instead of HttpClient whenever you need the additional features that HttpWebRequest provides. Further, unlike WebClient, HttpClient lacks support for progress reporting and custom URI schemes.&nbsp;<\/p>\n\n\n\n<p>Although HttpClient doesn\u2019t support FTP, mocking and testing HttpClient is easier. All I\/O bound methods in HttpClient are asynchronous, and you can use the same HttpClient instance to make concurrent requests as well.&nbsp;The following code snippet illustrates how you can work with HttpClient.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public<\/strong> async <strong>Task<\/strong>&lt;<strong>Author<\/strong>&gt; <strong>GetAuthorsAsync<\/strong>(<strong>string<\/strong> uri)<br>{<br>&nbsp; &nbsp; <strong>Author<\/strong> author = <strong>null<\/strong>;<br>&nbsp; &nbsp; <strong>HttpResponseMessage<\/strong> response = await client.<strong>GetAsync<\/strong>(uri);<br>&nbsp; &nbsp; <strong>if<\/strong> (response.<strong>IsSuccessStatusCode<\/strong>)<br>&nbsp; &nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; author = await response.<strong>Content<\/strong>.<strong>ReadAsAsync<\/strong>&lt;<strong>Author<\/strong>&gt;();<br>&nbsp; &nbsp; }<br>&nbsp; &nbsp; <strong>return<\/strong> author;<br>}<\/pre>\n\n\n\n<p>Note that when there is an error in the response, HttpClient doesn\u2019t throw an error. Rather, it sets the&nbsp;<code>IsSuccessStatusCode<\/code>&nbsp;property to false. If you want to throw an exception if the&nbsp;<code>IsSuccessStatusCode<\/code>&nbsp;property is false, you can make a call to the&nbsp;<code>EnsureSuccessStatusCode<\/code>&nbsp;method on the response instance as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">response.<strong>EnsureSuccessStatusCode<\/strong>();<\/pre>\n\n\n\n<p>HttpClient was designed to be instantiated once and reused throughout the application\u2019s lifecycle\u2014you should not create a new HttpClient instance for every request that your application needs to process. If you do, the available sockets could become exhausted by heavy traffic, resulting in&nbsp;<code>SocketException<\/code>&nbsp;errors. The recommended practice is to create a single, shared HttpClient instance.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a nutshell, WebRequest\u2014in its HTTP-specific implementation, HttpWebRequest\u2014represents the original way to consume HTTP requests in .NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,5,4,2],"tags":[],"_links":{"self":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/325"}],"collection":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/comments?post=325"}],"version-history":[{"count":2,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/325\/revisions"}],"predecessor-version":[{"id":327,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/325\/revisions\/327"}],"wp:attachment":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/media?parent=325"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/categories?post=325"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/tags?post=325"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}