C#?HttpClient超時重試機制詳解
更新時間:2023年06月10日 08:54:04 作者:涼生涼憶亦涼心
超時重試的實現(xiàn)方式可以使用循環(huán)結構,在請求發(fā)起后等待一定時間,若超時未收到響應,則再次發(fā)起請求,循環(huán)次數(shù)可以根據(jù)實際情況進行設置,一般建議不超過三次,這篇文章主要介紹了C#?HttpClient超時重試,需要的朋友可以參考下
c# HttpClient超時重試
當使用c# HttpClient 發(fā)送請求時,由于網(wǎng)絡等原因可能會出現(xiàn)超時的情況。為了提高請求的成功率,我們可以使用超時重試的機制。
超時重試的實現(xiàn)方式可以使用循環(huán)結構,在請求發(fā)起后等待一定時間,若超時未收到響應,則再次發(fā)起請求。循環(huán)次數(shù)可以根據(jù)實際情況進行設置,一般建議不超過三次。
百度搜索的關于c#HttpClient 的比較少,簡單整理了下,代碼如下
//調(diào)用方式 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;
///
/// 超時重試
///
///重試次數(shù)
///超時時間
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;
}
}到此這篇關于C# HttpClient超時重試的文章就介紹到這了,更多相關c# HttpClient超時重試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# wpf使用ListBox實現(xiàn)尺子控件的示例代碼
本文主要介紹了C# wpf使用ListBox實現(xiàn)尺子控件的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07

