There is several ways to consume a RESTful API in C #:
HttpWebRequest
/ Response
Class
WebClient
Class
HttpClient
Class
RestSharp
NuGet Package
ServiceStack
Http Utils
Httpwebrequest/response Class
HttpWebRequest request = (HttpWebRequest) webrequest.create ("https://api.github.com/repos/restsharp/restsharp/ Releases "); request. Method = "GET"; request. useragent = "mozilla/5.0 (Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/58.0.3029.110 safari/537.36 "; request. Automaticdecompression = Decompressionmethods.deflate | Decompressionmethods.gzip; HttpWebResponse response = (HttpWebResponse) request. GetResponse (); string content = String. Empty;using (Stream stream = response. GetResponseStream ()) {using (StreamReader sr = new StreamReader (stream)) {content = Sr. ReadToEnd ();}} var releases = Jarray.parse (content);
WebClient Class
var client = new WebClient (); client. Headers.add ("User-agent", "mozilla/5.0" (Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/58.0.3029.110 safari/537.36 "); var response = client. Downloadstring ("https://api.github.com/repos/restsharp/restsharp/releases"); var releases = Jarray.parse (response) ;
HttpClient Class
using (var httpClient = new HttpClient ()) {HTTPCLIENT.DEFAULTREQUESTHEADERS.ADD ("user-agent", "mozilla/5.0" ( Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/58.0.3029.110 safari/537.36 "); var response = Httpclient.getstringasync (new Uri (URL)). Result;var releases = Jarray.parse (response);}
Restsharp
RestSharp
Is the opensource alternative to standard. NET libraries and one of the coolest. NET libraries out there. It's available as a NuGet package, and there be a few reasons why you should consider trying it out.
Like HttpClient
, was RestSharp
a modern and comprehensive library, easy and pleasant to use, while still have support for older ver Sions of the. NET Framework. It has inbuilt authentication and serialization/deserialization mechanisms but allows you to override them with your Custo M ones. It is available across platforms and supports OAUTH1, OAuth2, Basic, NTLM and parameter-based authentication. It can also work synchronously or asynchronously. There is a lot of the library, but these is some of the great benefits it offers. For the detailed information on usage and capabilities of RESTSHARP, you can visit the Restsharp page on GitHub.
Now let's try to get a list of Restsharp releases using Restsharp.
var client = new Restclient (URL); irestresponse response = client. Execute (New Restrequest ()); var releases = Jarray.parse (response. Content);
ServiceStack Http Utils
var response = URL. Getjsonfromurl (Requestfilter:webreq =>{webreq.useragent = "mozilla/5.0" (Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/58.0.3029.110 safari/537.36 ";}"; var releases = Jarray.parse (response);
How to invoke the API