Calling Web API Using HttpClient

Calling Web API Using HttpClient

In this tutorial, we are going to create a checklist for different ways in Calling Web API Using HttpClient. In software development, data were passed through a different medium or application, and one of the best ways to handle it is to use Web Services and Apis. This is where we can make use of and utilizes the HttpClient request. This post will answer the question of how to Call Web API Using HttpClient.

This are the method available for HttpClient:

  1. CancelPendingRequests
  2. DeleteAsync
  3. GetAsync
  4. GetByteArrayAsync
  5. GetStreamAsync
  6. GetStringAsync
  7. PostAsync
  8. PutAsync
  9. SendAsync

Most front-end applications need to communicate with a server over HTTP protocol to download or upload data and access any back-end services. To do that, we need to create an HTTP request, and in this post, we will use HTTPClient.

We need to add HttpClient to our project. To do that, open NuGet Package Manager on your Visual Studio. After adding the package, we can declare its namespace, which is System.Net.Http.

Calling Web API Using HttpClient:

For us to have an idea of how HTTPClient works. We will create a sample request code on how to Call Web API Using HttpClient.

1. CancelPendingRequests

   public void PostWithCancelSyntax()
      {    
   using (var client = new HttpClient())
        {
            try
            {
                var content = new FormUrlEncodedContent(new[]
                        {
                               new KeyValuePair<string,string>("","parameter")
                         });
                var response =  client.PostAsync("/api/values", content).Result;
                MessageBox.Show(response.ToString());
                if (!response.IsSuccessStatusCode)
                {
                    MessageBox.Show("Error");
                }
            }
            catch (Exception Error)
            {
                MessageBox.Show(Error.Message);
            }
            finally
            {
                client.CancelPendingRequests();
            }
        }
    }

2. DeleteAsync

public static async Task<HttpResponseMessage> DeleteAsync(string endpoint)
        {
            HttpResponseMessage result;
            using (var client = new HttpClient())
            {
                try
                {
                    result = await client.DeleteAsync(endpoint);
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
            return result;
        }

3. GetAsync

  • The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
async static Task<string> getRequest(string url)
        {
            string con = "";
            using (HttpClient client = new HttpClient())
            { 
               using (HttpResponseMessage response = await client.GetAsync(url))
               {
                   using (HttpContent content = response.Content)
                   {
                        con = await content.ReadAsStringAsync();
                       MessageBox.Show(con);
                   }
               }
            }

            return con;
        }  

4. GetByteArrayAsync

private async Task<string> DownloadBase64(string url)
        {
            var bytes = await new HttpClient().GetByteArrayAsync(url);
            return Convert.ToBase64String(bytes);
        }

5. GetStreamAsync

 public static async Task<Stream> LoadServerResourceAsync(string url)
        {
            using (var _httpClient = new HttpClient())
            {
                var stream = await _httpClient.GetStreamAsync(url).ConfigureAwait(false);
                return stream;
            }
        }

6. GetStringAsync

public static  void GetStringAsyncMethod()
            {
                string uri = "http://localhost/api/values/1";
                HttpClient httpClient = new HttpClient();
                Task<string> response = httpClient.GetStringAsync(uri);
                string s = response.Result;
                
           }

7. PostAsync

  • The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
async static Task<string> PostRequest(string url)
        {
            string response = "";
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:33066");
                var content = new FormUrlEncodedContent(new[]
                {
                   new KeyValuePair<string,string>("","parameter")
                });

                var result = await client.PostAsync("/api/values", content);
                 response = await result.Content.ReadAsStringAsync();
            }

            return response;
        }

HTTPCLIENT Request with Try Catch to get the inner WebException messsage.

 async static Task<string> PostRequest(string url)
         {
             string response = "";
  
             try
             {
                 using (HttpClient client = new HttpClient())
                 {
                     client.BaseAddress = new Uri("http://localhost:33066");
                     var content = new FormUrlEncodedContent(new[]
                     {
                         new KeyValuePair<string,string>("","parameter")
                     });
  
                     var result = await client.PostAsync("/api/values", content);
                     response = await result.Content.ReadAsStringAsync();
                 }
             }
             catch (WebException ex)
             {
                 using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                 {
                     response = reader.ReadToEnd().ToString();
                 }
             }
  
             return response;
         } 

8. PutAsync

async static Task<string> PutRequest(string url)
            {
                string con = "";
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:33066");
                    var content = new FormUrlEncodedContent(new[]
                    {
                   new KeyValuePair<string,string>("","parameter")
                });

                    var result = await client.PutAsync("/api/values", content);
                    con = await result.Content.ReadAsStringAsync();
                }

                return con;
            }

9. SendAsync

 static async Task<string> 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;
        }

HttpClient reference can be added using the Nuget Package Manager of Visual Studio. And easily implement calling Web API Using HttpClient.

How to use WebClient in ASP.NET Application? Hopes this helps. Happy Coding!