get data from url in csharp

To get data from a URL in C#, you can use the HttpClient class in the .NET Framework.

Here's an example code snippet:

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

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://jsonplaceholder.typicode.com/todos/1";
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    string data = await content.ReadAsStringAsync();
                    Console.WriteLine(data);
                }
            }
        }
    }
}
601 chars
23 lines

In this example, we first create a URL string (url). Then we create an instance of HttpClient, and use the GetAsync method to send an HTTP GET request to the URL.

We then retrieve the response content using the ReadAsStringAsync method of the HttpContent object. Finally, we print the data to the console.

Note that the await keyword is used to await the asynchronous operations.

gistlibby LogSnag