c# HttpClient超时重试

发布时间 2023-06-09 08:59:49作者: 凉生凉忆亦凉心
             
            //调用方式 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;
            /// <summary>
            /// 超时重试
            /// </summary>
            /// <param name="max_count">重试次数</param>
            /// <param name="timeout">超时时间</param>
            public TimeoutHandler(int max_count = 3, int timeout = 5000)
            {
                base.InnerHandler = new HttpClientHandler();
                _timeout = timeout;
                _max_count = max_count;
            }

            protected async override Task<HttpResponseMessage> 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;
            }
        }