Consume Web APIs Using HttpClient with GET Method | Part 9

preview_player
Показать описание
Here you can learn how to Consume Web APIs Using HttpClient with GET Method.
Requirement: Visual studio 2015, SQL server 2012 or higher version
HttpClient:The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol.WebClient class had some limitations.
The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient.
Here, we will use HttpClient class in console application to send data to and receive data from Web API which is hosted on local IIS web server.

You may also use HttpClient in other .NET applications such as MVC Web Application, windows form application, windows service application etc.

Let us start:
Consider we have client web api
Method Name: Get
So we have to call this web api to our application, for simplicity I have taken here console application, let us see.
class Program
{
static void Main(string[] args)
{
Consume_WebAPI().Wait();
}

static async Task Consume_WebAPI()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = await client.GetAsync("api/employee/list");
if (response.IsSuccessStatusCode)
{
dynamic result = await response.Content.ReadAsStringAsync();
Rootobject rootObject = JsonConvert.DeserializeObject put here less sign Rootobject put here greater sign(result);

foreach (var item in rootObject.Employee)
{
}

Console.ReadKey();
}
}
}
public class Rootobject
{
public List put here less sign Employee put here greater sign Employee { get; set; }
}

public class Employee
{
public int empid { get; set; }
public string Name { get; set; }
public decimal salary { get; set; }
}
ReadAsStringAsync() Serialize the HTTP content to a string as an asynchronous operation.

Example:

{
"Employee": [
{
"empid": 106,
"Name": "Breylin",
"salary": 20000
},
{
"empid": 107,
"Name": "Breylin A",
"salary": 20000
},
{
"empid": 110,
"Name": "Breylin A",
"salary": 20000
},
{
"empid": 150,
"Name": "Ame",
"salary": 3000
}
]
}
Рекомендации по теме
Комментарии
Автор

Hi Sir, can you please guide on how to consume webapi by passing different parameters from database table as a request using http client. It’s little urgent. Thanks

sunshinelight