如何使用重试后标头使用asp.net http客户端轮询API [英] How to use the retry-after header to poll API using asp.net http client
问题描述
我对使用.net中的http客户端进行RESTful消费很陌生,并且在理解外部轮询API时如何使用retry-after标头时遇到了麻烦.
I'm kind of new to RESTful consumption using http client in .net and i'm having trouble understanding how to use the retry-after header when polling an external API.
这是我当前要轮询的内容:
This is what i have to poll currently:
HttpResponseMessage result = null;
var success = false;
var maxAttempts = 7;
var attempts = 0;
using (var client = new HttpClient())
{
do
{
var url = "https://xxxxxxxxxxxxxxx";
result = await client.GetAsync(url);
attempts++;
if(result.StatusCode == HttpStatusCode.OK || attempts == maxAttempts)
success = true;
}
while (!success);
}
return result;
如您所见,我一直在轮询端点,直到获得OK响应或达到最大尝试次数(停止连续循环)为止.
As you can see, i keep polling the endpoint until i've either got an OK response or the max attempts has been reached (to stop continuous looping).
如何使用响应中的retry-after标头来指示循环中每个调用之间等待的时间?
How can i use the retry-after header from the response i get to dictate how long i wait between each of the calls in the loop?
我只是想不出如何将其应用于我的情况.
I just cant work out how to apply this to my situation.
谢谢
推荐答案
HttpClient
is intended to be instantiated once per application, rather than per-use
private static HttpClient client = new HttpClient();
方法(已更新HTTP主机头用法)
The method (updated with HTTP Host Header usage)
private static async Task<string> GetDataWithPollingAsync(string url, int maxAttempts, string host = null)
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
{
if (host?.Length > 0) request.Headers.Host = host;
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
TimeSpan delay = default;
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
delay = response.Headers.RetryAfter.Delta ?? TimeSpan.FromSeconds(1);
}
await Task.Delay(delay);
}
}
throw new Exception("Failed to get data from server");
}
用法
try
{
string result = await GetDataWithPollingAsync("http://some.url", 7, "www.example.com");
// received
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
// failed
}
这篇关于如何使用重试后标头使用asp.net http客户端轮询API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!