在C#中,您可以使用HttpClient
类来发送HTTP请求并设置超时。以下是一个示例,展示了如何设置连接超时和读取超时:
using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // 创建一个新的HttpClient实例 using (HttpClient httpClient = new HttpClient()) { // 设置连接超时和读取超时 httpClient.Timeout = TimeSpan.FromSeconds(10); // 10秒 try { // 发送HTTP请求 HttpResponseMessage response = await httpClient.GetAsync("https://api.example.com/data"); // 读取响应内容 response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Response: " + responseBody); } catch (HttpRequestException e) { Console.WriteLine("Error: " + e.Message); } } } }
在这个示例中,我们创建了一个HttpClient
实例,并使用Timeout
属性设置了连接超时和读取超时为10秒。然后,我们使用GetAsync
方法发送一个HTTP GET请求,并在try
块中读取响应内容。如果发生任何错误,我们将在catch
块中捕获HttpRequestException
异常并输出错误信息。