like Gecko) Chrome/58.0.3029.110 Safari/537.36";request.Aut

时间:2022-02-07 07:50:15

There are 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 is available as a NuGet package, and there are a few reasons why you should consider trying it out.

Like HttpClient, RestSharp is a modern and comprehensive library, easy and pleasant to use, while still having support for older versions of .NET Framework. It has inbuilt Authentication and Serialization/Deserialization mechanisms but allows you to override them with your custom 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 more to this library, but these are 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);