c# HttpClient超时重试

当使用c# HttpClient 发送请求时,由于网络等原因可能会出现超时的情况。为了提高请求的成功率,我们可以使用超时重试的机制。

超时重试的实现方式可以使用循环结构,在请求发起后等待一定时间,若超时未收到响应,则再次发起请求。循环次数可以根据实际情况进行设置,一般建议不超过三次。

百度搜索的关于c#HttpClient 的比较少,简单整理了下,代码如下

            //调用方式 3秒后超时 重试2次        .net framework 4.5               
             HttpMessageHandler handler = new TimeoutHandler(2,3000);
                    using (var client = new HttpClient(handler))
                    {
                        using (var content = new StringContent(""), null, "application/json"))
                        {
                            var response = client.PostAsync("url", content).Result;
                            string result = response.Content.ReadAsStringAsync().Result;
                            JObject jobj = JObject.Parse(result);
                            if (jobj.Value<int>("code") == 1)
                            {
                            }
                        }
                    }
public class TimeoutHandler : DelegatingHandler
{
    private int _timeout;
    private int _max_count;
    ///
    /// 超时重试
    /// 
    ///重试次数
    ///超时时间
    public TimeoutHandler( int max_count = 3,  int timeout = 5000)
    {
        base .InnerHandler =  new HttpClientHandler();
        _timeout = timeout;
        _max_count = max_count;
    }

    protected async  override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response =  null ;
        for ( int i = 1; i <= _max_count + 1; i++)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            cts.CancelAfter(_timeout);
            try
            {
                 response = await  base .SendAsync(request, cts.Token);

                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
            }
            catch (Exception ex)
            {
                //请求超时
                if (ex  is TaskCanceledException)
                {
                    MyLogService.Print( "接口请求超时:" + ex.ToString());
                    if (i > _max_count)
                    {
                        return new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content =  new StringContent( "{\"code\":-1,\"data\":\"\",\"msg\":\"接口请求超时\"}" , Encoding.UTF8,  "text/json" )
                        };
                    }
                    MyLogService.Print($ "接口第{i}次重新请求" );
                }
                else
                {
                    MyLogService.Error( "接口请求出错:" + ex.ToString());
                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content =  new StringContent( "{\"code\":-1,\"data\":\"\",\"msg\":\"接口请求出错\"}" , Encoding.UTF8,  "text/json" )
                    };
                }
            }
        }
        return response;
    }
}

  

posted @ 2023-06-09 08:53  凉生凉忆亦凉心  阅读(735)  评论(2编辑  收藏  举报