using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
try
{
// 发送GET请求并获取响应
HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
// 捕获HTTP请求异常并输出错误信息
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}
HttpClient 是线程安全的,建议在整个应用程序中重用同一个实例。HttpResponseMessage 对象。HttpClient 在使用完毕后被正确释放资源。这个示例展示了如何使用C#中的 HttpClient 类来发送HTTP GET请求,并处理响应。
上一篇:c# rabbitmq
下一篇:c# 数组初始化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站