Introduction

In today’s connected world, interacting with web services and APIs is a common task in application development. The HttpClient class in C# provides a powerful and flexible way to make HTTP requests and handle responses. In this post, we will explore how to use HttpClient to perform various HTTP operations such as GET, POST, PUT, and DELETE, with practical examples to help you integrate these operations into your applications.

Setting Up HttpClient

Before using HttpClient, ensure you have the necessary using directive in your file:

using System;
using System.Net.Http;
using System.Threading.Tasks;

The HttpClient class is included in the System.Net.Http namespace, which is part of the .NET Framework and .NET Core by default, so no additional references are needed.

Performing HTTP GET Requests

The GET method requests data from a specified resource. Here’s how to perform a GET request using HttpClient:

Example: HTTP GET Request

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await GetRequest();
    }

    public static async Task GetRequest()
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Explanation:

  • HttpClient: A single instance of HttpClient is created and reused to make multiple requests.
  • GetAsync: Sends a GET request to the specified URL.
  • EnsureSuccessStatusCode: Throws an exception if the HTTP response indicates an unsuccessful status code.
  • ReadAsStringAsync: Reads the response content as a string.

Output:

{
  "userId": 1,
  "id": 1,
  "title": "Sample Title",
  "body": "Sample Body"
}

Performing HTTP POST Requests

The POST method submits data to be processed to a specified resource. Here’s how to perform a POST request using HttpClient:

Example: HTTP POST Request

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await PostRequest();
    }

    public static async Task PostRequest()
    {
        var postData = new StringContent(
            "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}",
            Encoding.UTF8,
            "application/json");

        try
        {
            HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", postData);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Explanation:

  • StringContent: Prepares the data to be sent in the POST request, setting the appropriate content type (e.g., application/json).
  • PostAsync: Sends a POST request to the specified URL with the provided data.

Output:

{
  "id": 101
}

Performing HTTP PUT Requests

The PUT method updates a current resource with new data. Here’s how to perform a PUT request using HttpClient:

Example: HTTP PUT Request

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await PutRequest();
    }

    public static async Task PutRequest()
    {
        var updateData = new StringContent(
            "{\"id\":1,\"title\":\"foo updated\",\"body\":\"bar updated\",\"userId\":1}",
            Encoding.UTF8,
            "application/json");

        try
        {
            HttpResponseMessage response = await client.PutAsync("https://jsonplaceholder.typicode.com/posts/1", updateData);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Explanation:

  • PutAsync: Sends a PUT request to the specified URL with the provided data, updating the resource.

Output:

{
  "id": 1,
  "title": "foo updated",
  "body": "bar updated",
  "userId": 1
}

Performing HTTP DELETE Requests

The DELETE method removes a specified resource. Here’s how to perform a DELETE request using HttpClient:

Example: HTTP DELETE Request

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await DeleteRequest();
    }

    public static async Task DeleteRequest()
    {
        try
        {
            HttpResponseMessage response = await client.DeleteAsync("https://jsonplaceholder.typicode.com/posts/1");
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Resource deleted successfully.");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Explanation:

  • DeleteAsync: Sends a DELETE request to the specified URL.

Output:

Resource deleted successfully.

Conclusion

Using HttpClient in C# allows you to interact with web APIs and perform HTTP operations seamlessly. Whether you are fetching data, submitting new data, updating existing data, or deleting resources, HttpClient provides a robust and flexible way to handle these tasks.

Full Example Code

Here’s the complete code combining all the examples for making HTTP GET, POST, PUT, and DELETE requests using HttpClient in C#:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await GetRequest();
        await PostRequest();
        await PutRequest();
        await DeleteRequest();
    }

    public static async Task GetRequest()
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("GET Response:");
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }

    public static async Task PostRequest()
    {
        var postData = new StringContent(
            "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}",
            Encoding.UTF8,
            "application/json");

        try
        {
            HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", postData);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("POST Response:");
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }

    public static async Task PutRequest()
    {
        var updateData = new StringContent(
            "{\"id\":1,\"title\":\"foo updated\",\"body\":\"bar updated\",\"userId\":1}",
            Encoding.UTF8,
            "application/json");

        try
        {
            HttpResponseMessage response = await client.PutAsync("https://jsonplaceholder.typicode.com/posts/1", updateData);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine("PUT Response:");
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }

    public static async Task DeleteRequest()
    {
        try
        {
            HttpResponseMessage response = await client.DeleteAsync("https://jsonplaceholder.typicode.com/posts/1");
            response.EnsureSuccessStatusCode();
            Console.WriteLine("DELETE Response:");
            Console.WriteLine("Resource deleted successfully.");
        }
        catch (HttpRequestException e)


 {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Similar Posts