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请求到指定URL
HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
// 捕获并处理请求异常
Console.WriteLine($"请求错误: {e.Message}");
}
}
}
}
try-catch块捕获并处理可能的HTTP请求异常。上一篇:c# log
下一篇:c# 读取配置文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站