Get the JSON in Console Application Using HttpClient

The HTTP Client  is used to call the API in console application or any another .NET application, Here is the example to implement it.

Http request

GET: /api/Employees/

Response 

 
HttpClient

It is a class which is from System.Net.Http Namespace and provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. 

Complete Code:

  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            Task T = new Task(ApiCall);  
  6.            T.Start();  
  7.            Console.WriteLine("Json data........");  
  8.            Console.ReadLine();  
  9.        }  
  10.        static async void ApiCall()  
  11.        {  
  12.   
  13.            using (var client = new HttpClient())  
  14.            {  
  15.   
  16.                HttpResponseMessage response = await client.GetAsync("http://localhost:57135/api/Employees/");  
  17.   
  18.                response.EnsureSuccessStatusCode();  
  19.   
  20.                using (HttpContent content = response.Content)  
  21.                {  
  22.                    string responseBody = await response.Content.ReadAsStringAsync();  
  23.   
  24.                    Console.WriteLine(responseBody.Substring(0, 50) + "........");  
  25.   
  26.                    var articles = JsonConvert.DeserializeObject<List<Employee>>(responseBody);  
  27.   
  28.   
  29.   
  30.                    foreach (var Emp in articles)  
  31.                    {  
  32.                        Console.WriteLine("{0}\t{1}\t{2}\t{3}", Emp.EmployeeId, Emp.FirstName, Emp.LastName, Emp.Age);  
  33.                    }  
  34.   
  35.                }  
  36.   
  37.            }    
  38.        }  

Output:

 
 
I hope you enjoyed this blog. Your valuable feedback, question, or comments about this blog are always welcomed. 
Ebook Download
View all
Learn
View all