在C#中,可以使用HttpClient类来发起GET请求。以下是一个简单的示例代码:
using System;using System.Net.Http;using System.Threading.Tasks;class Program{ static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("https://api.example.com/data"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine("Failed to make request. Status code: " + response.StatusCode); } } }}在这个示例中,我们首先创建了一个HttpClient对象,然后使用GetAsync方法发起GET请求,并等待获取响应。如果请求成功,则读取响应内容并打印出来,否则打印错误消息。
需要注意的是,在使用HttpClient类时需要进行适当的错误处理和资源释放,确保程序的稳定性和性能。