Sobes.tech
Junior — Middle

Do you have experience using the HttpClient library for making HTTP requests?

sobes.tech AI

Answer from AI

Yes, the HttpClient library in C# is widely used for making HTTP requests. It provides a convenient and asynchronous API for sending GET, POST, PUT, DELETE, and other requests.

Example of a simple GET request using HttpClient:

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

class Program
{
    static async Task Main()
    {
        using HttpClient client = new HttpClient();
        try
        {
            string url = "https://api.example.com/data";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
        }
    }
}

HttpClient supports header configuration, timeouts, sending data in the request body, and much more.