HttpClient GetAsync, PostAsync, SendAsync in C#

2 Comments

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));

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

2 Responses to HttpClient GetAsync, PostAsync, SendAsync in C#

  1. if your auth goes in the header like this -> client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, “huge long token”); this is after you instantiate HttpClient

Leave a Reply

Your email address will not be published. Required fields are marked *