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

   2024-10-06 9790
核心提示:在C#中,可以使用HttpClient类来发送GET请求并设置超时时间。以下是一个示例代码:using System;using System.Net.Http;using Sy

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号