翼度科技»论坛 编程开发 .net 查看内容

c# HttpClient超时重试

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
当使用c# HttpClient 发送请求时,由于网络等原因可能会出现超时的情况。为了提高请求的成功率,我们可以使用超时重试的机制。
超时重试的实现方式可以使用循环结构,在请求发起后等待一定时间,若超时未收到响应,则再次发起请求。循环次数可以根据实际情况进行设置,一般建议不超过三次。
百度搜索的关于c#HttpClient 的比较少,简单整理了下,代码如下
  1. <em id="__mceDel">            //调用方式 3秒后超时 重试2次        .net framework 4.5               
  2.             HttpMessageHandler handler = new TimeoutHandler(2,3000);
  3.                     using (var client = new HttpClient(handler))
  4.                     {
  5.                         using (var content = new StringContent(""), null, "application/json"))
  6.                         {
  7.                             var response = client.PostAsync("url", content).Result;
  8.                             string result = response.Content.ReadAsStringAsync().Result;
  9.                             JObject jobj = JObject.Parse(result);
  10.                             if (jobj.Value<int>("code") == 1)
  11.                             {
  12.                             }
  13.                         }
  14.                     }</em>
复制代码
  1. public class TimeoutHandler : DelegatingHandler
  2. {
  3.     private int _timeout;
  4.     private int _max_count;
  5.     ///
  6.     /// 超时重试
  7.     ///
  8.     ///重试次数
  9.     ///超时时间
  10.     public TimeoutHandler( int max_count = 3,  int timeout = 5000)
  11.     {
  12.         base .InnerHandler =  new HttpClientHandler();
  13.         _timeout = timeout;
  14.         _max_count = max_count;
  15.     }
  16.     protected async  override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  17.     {
  18.         HttpResponseMessage response =  null ;
  19.         for ( int i = 1; i <= _max_count + 1; i++)
  20.         {
  21.             var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  22.             cts.CancelAfter(_timeout);
  23.             try
  24.             {
  25.                  response = await  base .SendAsync(request, cts.Token);
  26.                 if (response.IsSuccessStatusCode)
  27.                 {
  28.                     return response;
  29.                 }
  30.             }
  31.             catch (Exception ex)
  32.             {
  33.                 //请求超时
  34.                 if (ex  is TaskCanceledException)
  35.                 {
  36.                     MyLogService.Print( "接口请求超时:" + ex.ToString());
  37.                     if (i > _max_count)
  38.                     {
  39.                         return new HttpResponseMessage(HttpStatusCode.OK)
  40.                         {
  41.                             Content =  new StringContent( "{"code":-1,"data":"","msg":"接口请求超时"}" , Encoding.UTF8,  "text/json" )
  42.                         };
  43.                     }
  44.                     MyLogService.Print($ "接口第{i}次重新请求" );
  45.                 }
  46.                 else
  47.                 {
  48.                     MyLogService.Error( "接口请求出错:" + ex.ToString());
  49.                     return new HttpResponseMessage(HttpStatusCode.OK)
  50.                     {
  51.                         Content =  new StringContent( "{"code":-1,"data":"","msg":"接口请求出错"}" , Encoding.UTF8,  "text/json" )
  52.                     };
  53.                 }
  54.             }
  55.         }
  56.         return response;
  57.     }
  58. }
复制代码
  

来源:https://www.cnblogs.com/xxxin/archive/2023/06/09/17468171.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具