Надсилання HTTP-запиту

C#:
Надсилання HTTP-запиту

How to: (Як зробити:)

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

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            try
            {
                // Sending a GET request to example.com
                HttpResponseMessage response = await client.GetAsync("http://example.com");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine(responseBody);  // Outputs the retrieved HTML
            }
            catch(HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message: {0} ", e.Message);
            }
        }
    }
}

Sample output:

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    ...
</head>
<body>
    ...
</body>
</html>

Deep Dive (Поглиблене Вивчення):

HTTP requests are foundational to web communication, established by Tim Berners-Lee in 1989. Alternatives like gRPC or WebSockets are used when you need real-time communication or other protocols.

Implementing an HTTP request in C# is straightforward thanks to the HttpClient class. Released with .NET Framework 4.5, HttpClient provides an async API for sending HTTP requests. Keep in mind to dispose of HttpClient instances to avoid resource leaks, or better yet, use a single instance throughout your app.

Another thing to consider is handling exceptions. With proper exception handling, your app can gracefully deal with network issues or bad responses.

In older C# versions, developers had to use WebRequest and WebResponse classes which were more cumbersome. HttpClient is not only easier to use but also supports modern async programming paradigms.

See Also (Дивіться також):