温馨提示×

C#中如何使用HttpClient发送GET请求

c#
小樊
260
2024-07-18 19:00:24
栏目: 编程语言

在C#中使用HttpClient发送GET请求可以使用以下代码示例:

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

class Program
{
    static async Task Main()
    {
        using (HttpClient client = new HttpClient())
        {
            // 设置请求的URL
            string url = "https://api.example.com/data";

            // 发送GET请求并获取响应
            HttpResponseMessage response = await client.GetAsync(url);

            // 检查响应是否成功
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                
                // 输出响应内容
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine($"Failed to make a GET request. Status code: {response.StatusCode}");
            }
        }
    }
}

在上面的示例中,我们创建了一个HttpClient实例并使用GetAsync方法发送GET请求。然后,我们检查响应的状态码是否为成功,并读取响应内容。最后,我们输出响应内容或者错误信息。

0