繁体   English   中英

如何使用重试后 header 轮询 API 使用 asp.net Z80791B3AE7002CB88F8C2468 客户端

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

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.

这是我目前必须调查的:

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

我如何从响应中使用重试 header 来指示我在循环中的每个调用之间等待多长时间?

我只是无法弄清楚如何将其应用于我的情况。

谢谢,

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

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM