在C#中,可以使用HttpClient类来发送GET请求并设置超时时间。以下是一个示例代码:
using System;using System.Net.Http;using System.Threading.Tasks;class Program{ static async Task Main(string[] args) { HttpClient client = new HttpClient(); // 设置超时时间为10秒 client.Timeout = TimeSpan.FromSeconds(10); try { HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1"); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request failed: {e.Message}"); } }}在上面的示例中,我们使用HttpClient类发送了一个GET请求,并设置超时时间为10秒。如果请求在超时时间内没有得到响应,将会抛出HttpRequestException异常。