當使用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; } }