make a http get request in csharp

To make an HTTP GET request in C#, you can use the HttpClient class from the System.Net.Http namespace. Here is an example code:

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

public class HttpExample
{
    public static async Task<string> MakeGetRequest(string url)
    {
        using (var client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
    }

    static void Main()
    {
        string url = "https://www.example.com/";
        string response = MakeGetRequest(url).GetAwaiter().GetResult();
        Console.WriteLine(response);
    }
}
663 chars
25 lines

This code creates an instance of HttpClient and uses its GetAsync method to send a GET request to the specified URL. The response is returned as an HttpResponseMessage object, from which you can extract the response body as a string using the ReadAsStringAsync method. In this example code, the main function calls the MakeGetRequest function and prints the response to the console.

related categories

gistlibby LogSnag