如何使用 retry-after header 通过 asp.net http 客户端轮询 API

How to use the retry-after header to poll API using asp.net http client

我对在 .net 中使用 http 客户端消费 RESTful 有点陌生,我无法理解如何在轮询外部 retry-after header 时使用 header =29=].

这是我目前要投票的内容:

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 响应或达到最大尝试次数(以停止连续循环)。

我如何使用我得到的响应中的 retry-after header 来指示我在循环中的每个调用之间等待多长时间?

我不知道如何将它应用到我的情况中。

谢谢,

HttpClient 旨在为每个应用程序实例化一次,而不是 per-use

private static HttpClient client = new HttpClient();

方法(更新为 HTTP 主机 Header 用法)

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
}