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) { } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)