read data http in csharp

To perform an HTTP request and read data in C#, you can use the HttpClient class provided in the System.Net.Http namespace.

Here is an example code block that demonstrates how to make a GET request to a URL and read the response as a string:

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

public class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient();
        var response = await client.GetAsync("https://example.com");

        if (response.IsSuccessStatusCode) 
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        } 
        else 
        {
            Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
        }
    }
}
568 chars
23 lines

In the above code, the HttpClient class is used to send an HTTP GET request to the given URL. The GetAsync method returns a Task<HttpResponseMessage> object that represents the asynchronous operation of sending the request and receiving the response.

We check if the response is successful using the IsSuccessStatusCode property. If it is successful, we can read the response content using the ReadAsStringAsync method of the HttpContent class.

If an error occurs, we print a failure message along with the status code.

related categories

gistlibby LogSnag