Http Client in C#

Here’s the translation of the HTTP Client example from Go to C#, formatted in Markdown suitable for Hugo:

Our example demonstrates how to create a simple HTTP client using C#. We’ll use the System.Net.Http namespace, which provides excellent support for HTTP clients.

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

class Program
{
    static async Task Main()
    {
        // Create an instance of HttpClient
        using var client = new HttpClient();

        try
        {
            // Send an HTTP GET request to a server
            HttpResponseMessage response = await client.GetAsync("https://gobyexample.com");

            // Ensure we get a successful status code
            response.EnsureSuccessStatusCode();

            // Print the HTTP response status
            Console.WriteLine($"Response status: {(int)response.StatusCode} {response.StatusCode}");

            // Read and print the first 5 lines of the response body
            string content = await response.Content.ReadAsStringAsync();
            string[] lines = content.Split('\n');
            for (int i = 0; i < Math.Min(5, lines.Length); i++)
            {
                Console.WriteLine(lines[i]);
            }
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
        }
    }
}

In this example, we’re using HttpClient to send an HTTP GET request. Here’s a breakdown of what the code does:

  1. We create an instance of HttpClient within a using statement to ensure it’s properly disposed.

  2. We use the GetAsync method to send a GET request to “https://gobyexample.com”. This method returns a Task<HttpResponseMessage>, which we await.

  3. We call EnsureSuccessStatusCode() to throw an exception if the response status code does not indicate success.

  4. We print the response status using the StatusCode property of the response.

  5. To read the response body, we use ReadAsStringAsync() method.

  6. We split the content into lines and print the first 5 lines.

  7. All of this is wrapped in a try-catch block to handle any HttpRequestException that might occur during the request.

To run this program, save it as HttpClient.cs and use the dotnet command:

$ dotnet run HttpClient.cs
Response status: 200 OK
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>

This example demonstrates basic HTTP client functionality in C#. The HttpClient class provides many more methods and options for more complex HTTP operations.