using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建HttpClient实例,用于发送HTTP请求
using (HttpClient client = new HttpClient())
{
try
{
// 定义API的URL
string apiUrl = "https://api.example.com/data";
// 发送GET请求并获取响应
HttpResponseMessage response = await client.GetAsync(apiUrl);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
// 捕获并处理HTTP请求异常
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}
try-catch块捕获并处理可能的HTTP请求异常。如果你需要调用其他类型的API(如POST、PUT等),可以使用PostAsync、PutAsync等方法,并根据需要传递请求体。
上一篇:c#字符串转byte数组
下一篇:c#索引器
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站