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.
In this example, we’re using HttpClient
to send an HTTP GET request. Here’s a breakdown of what the code does:
We create an instance of
HttpClient
within ausing
statement to ensure it’s properly disposed.We use the
GetAsync
method to send a GET request to “https://gobyexample.com”. This method returns aTask<HttpResponseMessage>
, which we await.We call
EnsureSuccessStatusCode()
to throw an exception if the response status code does not indicate success.We print the response status using the
StatusCode
property of the response.To read the response body, we use
ReadAsStringAsync()
method.We split the content into lines and print the first 5 lines.
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:
This example demonstrates basic HTTP client functionality in C#. The HttpClient
class provides many more methods and options for more complex HTTP operations.