使用HttpClient库的C#程序示例
作者:野牛程序员:2023-12-28 15:51:48C#阅读 2740
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await MakeRequest();
}
static async Task MakeRequest()
{
using (HttpClient client = new HttpClient())
{
try
{
// 设置要访问的API地址
string apiUrl = "https://api.example.com";
// 发送GET请求
HttpResponseMessage response = await client.GetAsync(apiUrl);
// 检查响应是否成功
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("API响应:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"发生异常:{ex.Message}");
}
}
}
}上述示例中使用了HttpClient来发送GET请求,并异步等待响应。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

