using System;
using System.Net.Http;
using System.Threading.Tasks;
//use newtonsoft to convert json to c# objects. Install with nuget
// using Newtonsoft.Json.Linq;
namespace FetchWebData
{
class Program
{
// static async void Main(string[] args)
static async Task Main(string[] args)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
//In the next using statement you will initiate the Get Request, use the await keyword so it will execute the using statement in order.
//The HttpResponseMessage which contains status code, and data from response.
using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync("https://www.example.com"))
{
//_ = await httpClient.GetAsync("https://www.example.com");
//Console.WriteLine("Hello World!");
//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.
// This is not await
using (HttpContent content = httpResponseMessage.Content)
{
var data = await content.ReadAsStringAsync();
if (data != null)
{
//Now log your data in the console
Console.WriteLine("data------------{0}", data);
//
// Console.WriteLine("data------------{0}", JObject.Parse(data)["results"]);
}
else
{
Console.WriteLine("NO Data----------");
}
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("Exception Hit------------");
Console.WriteLine(exception);
}
}
}
}
Comments