C#?HttpClient超時重試機制詳解
c# HttpClient超時重試
當(dāng)使用c# HttpClient 發(fā)送請求時,由于網(wǎng)絡(luò)等原因可能會出現(xiàn)超時的情況。為了提高請求的成功率,我們可以使用超時重試的機制。
超時重試的實現(xiàn)方式可以使用循環(huán)結(jié)構(gòu),在請求發(fā)起后等待一定時間,若超時未收到響應(yīng),則再次發(fā)起請求。循環(huán)次數(shù)可以根據(jù)實際情況進行設(shè)置,一般建議不超過三次。
百度搜索的關(guān)于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;
}
}到此這篇關(guān)于C# HttpClient超時重試的文章就介紹到這了,更多相關(guān)c# HttpClient超時重試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)給Word每一頁設(shè)置不同文字水印的方法詳解
Word中設(shè)置水印時,可使用預(yù)設(shè)的文字或自定義文字設(shè)置為水印效果,但通常添加水印效果時,會對所有頁面都設(shè)置成統(tǒng)一效果。本文以C#?代碼為例,對Word每一頁設(shè)置不同的文字水印效果作詳細介紹,感興趣的可以了解一下2022-07-07
selenium.chrome寫擴展攔截或轉(zhuǎn)發(fā)請求功能
Selenium?WebDriver?是一組開源?API,用于自動測試?Web?應(yīng)用程序,利用它可以通過代碼來控制chrome瀏覽器,今天通過本文給大家介紹selenium?chrome寫擴展攔截或轉(zhuǎn)發(fā)請求功能,感興趣的朋友一起看看吧2022-07-07
C#代碼實現(xiàn)在PowerPoint中創(chuàng)建編號或項目符號列表
列表是 PowerPoint 演示文稿中非常實用的工具,在本文中,我們將介紹如何使用 Spire.Presentation for .NET 在 C# 和 VB.NET 中創(chuàng)建 編號列表 和 項目符號列表,需要的可以了解下2026-02-02

