c#

C#中如何为GET请求设置超时

小樊
162
2024-07-18 18:57:30
栏目: 编程语言

在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异常。

0
看了该问题的人还看了