Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

HTTP Client in C# - Comprehensive Tutorial

Introduction

In this tutorial, we will explore how to use the HttpClient class in C# to make HTTP requests. This class is provided by the .NET framework and is essential for making web requests in a modern and efficient manner.

Setting Up

Before we start, ensure you have the .NET SDK installed on your machine. You can download it from the official .NET website.

To create a new console application, open your terminal and run the following command:

dotnet new console -n HttpClientExample

Basic GET Request

Let's start with a simple GET request to fetch data from a web server. Add the following code to your Program.cs file:

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

namespace HttpClientExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
}
                

This code creates an instance of HttpClient, makes a GET request to a sample API, and prints the response body to the console.

Handling Exceptions

It's important to handle exceptions when making HTTP requests. Here is an improved version of the previous example with error handling:

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

namespace HttpClientExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    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($"Request error: {e.Message}");
            }
        }
    }
}
                

In this version, we catch HttpRequestException and print an error message if the request fails.

POST Request

Now, let's see how to make a POST request to send data to a server. Add the following code to your Program.cs file:

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

namespace HttpClientExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                var postData = new StringContent("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}", Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", postData);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
}
                

This code creates a JSON payload and sends it to the server using the PostAsync method.

Adding Headers

Sometimes, you may need to add headers to your HTTP requests. Here's how you can add custom headers:

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

namespace HttpClientExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_TOKEN_HERE");
                
                HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
}
                

This example adds an Authorization header to the GET request.

Conclusion

In this tutorial, we covered the basics of using HttpClient in C#. We learned how to make GET and POST requests, handle exceptions, and add custom headers. With these fundamentals, you can start integrating HTTP requests into your C# applications.