Advertisement
wingman007

FetchWebDataAsyncAwait

Oct 6th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. //use newtonsoft to convert json to c# objects. Install with nuget
  5. // using Newtonsoft.Json.Linq;
  6.  
  7. namespace FetchWebData
  8. {
  9.     class Program
  10.     {
  11.         // static async void Main(string[] args)
  12.         static async Task Main(string[] args)
  13.         {
  14.             try
  15.             {
  16.                 using (HttpClient httpClient = new HttpClient())
  17.                 {
  18.                     //In the next using statement you will initiate the Get Request, use the await keyword so it will execute the using statement in order.
  19.                     //The HttpResponseMessage which contains status code, and data from response.
  20.                     using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync("https://www.example.com"))
  21.                     {
  22.                         //_ = await httpClient.GetAsync("https://www.example.com");
  23.                         //Console.WriteLine("Hello World!");
  24.                         //Then get the data or content from the response in the next using statement, then within it you will get the data, and convert it to a c# object.
  25.                         // This is not await
  26.                         using (HttpContent content = httpResponseMessage.Content)
  27.                         {
  28.                             var data = await content.ReadAsStringAsync();
  29.  
  30.                             if (data != null)
  31.                             {
  32.                                 //Now log your data in the console
  33.                                 Console.WriteLine("data------------{0}", data);
  34.                                 //
  35.                                 // Console.WriteLine("data------------{0}", JObject.Parse(data)["results"]);
  36.                             }
  37.                             else
  38.                             {
  39.                                 Console.WriteLine("NO Data----------");
  40.                             }
  41.                         }
  42.                     }
  43.                 }
  44.             }
  45.             catch (Exception exception)
  46.             {
  47.  
  48.                 Console.WriteLine("Exception Hit------------");
  49.                 Console.WriteLine(exception);
  50.             }
  51.  
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement