HttpClient is a library in the Microsoft .NET framework 4+ that is used for GET and POST requests. Let’s go through a simple example of using HttpClient to GET and POST JSON from a web application.
First, we will create our client application. We will create a new console app in Visual Studio:
Add the System.Net.Http namespace. We will pull down JSON data from a REST service:
Now, to read this, we can define a new function to get a URI using HttpClient. This uses async which blocks until the call is complete:
static async Task<string> GetURI(Uri u) { var response = string.Empty; using (var client = new HttpClient()) { HttpResponseMessage result = await client.GetAsync(u); if (result.IsSuccessStatusCode) { response = await result.Content.ReadAsStringAsync(); } } return response; }
We can call our new function by:
var t = Task.Run(() => GetURI(new Uri("http://localhost:31404/Api/Customers"))); t.Wait(); Console.WriteLine(t.Result); Console.ReadLine();
This receives a response from our web service and displays it in the console:
To parse out the returned JSON, add a reference to Newtonsoft:
Change the code to use JArray using Newtonsoft.Json.Linq:
var t = Task.Run(() => GetURI(new Uri("http://localhost:31404/Api/Customers"))); t.Wait(); JArray j = JArray.Parse(t.Result); Console.WriteLine(j); Console.ReadLine();
This now looks like:
Now, to create a new record using our REST service, we will use HttpPost with HttpClient PostAsync.
We will create a function PostURI which calls HttpClient PostAsync, then returns the StatusCode:
static async Task<string> PostURI(Uri u, HttpContent c) { var response = string.Empty; using (var client = new HttpClient()) { HttpResponseMessage result = await client.PostAsync(u, c); if (result.IsSuccessStatusCode) { response = result.StatusCode.ToString(); } } return response; }
We will call it by creating a string that we will use to post:
Uri u = new Uri("http://localhost:31404/Api/Customers"); var payload = "{\"CustomerId\": 5,\"CustomerName\": \"Pepsi\"}"; HttpContent c = new StringContent(payload, Encoding.UTF8, "application/json"); var t = Task.Run(() => PostURI(u, c)); t.Wait(); Console.WriteLine(t.Result); Console.ReadLine();
Running this produces:
The backend database shows the new record created:
Using SendAsync, we can write the code as:
static async Task SendURI(Uri u, HttpContent c) { var response = string.Empty; using (var client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = u, Content = c }; HttpResponseMessage result = await client.SendAsync(request); if (result.IsSuccessStatusCode) { response = result.StatusCode.ToString(); } } return response;
Calling it:
Uri u = new Uri("http://localhost:31404/Api/Customers"); var payload = "{\"CustomerId\": 5,\"CustomerName\": \"Pepsi\"}"; HttpContent c = new StringContent(payload, Encoding.UTF8, "application/json"); var t = Task.Run(() => SendURI(u, c)); t.Wait(); Console.WriteLine(t.Result); Console.ReadLine();
Note instead of sending a JSON string, we can create a class/object and serialize it:
var payload = new Dictionary<string, string> { {"CustomerId", "5"}, {"CustomerName", "Pepsi"} }; string strPayload = JsonConvert.SerializeObject(payload); HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/json"); var t = Task.Run(() => SendURI(u, c));
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL
How to do i pass basic Auth in above code?
if your auth goes in the header like this -> client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, “huge long token”); this is after you instantiate HttpClient
Very helpful post, Appreciate you effort.
Hello,
Do you have the completed solution available to download?
Thanks
Hi Carl, I’m getting the status of post Async as “Awaiting Activation”. Any pointers on how to resolve it.
Thanks a lot! You are the best!