如何从有时会抛出超时异常的端点获取响应

时间:2016-11-29 09:01:19

标签: c# http

有一个第三方API应该返回大量的短信。我不知道它对于特定查询有多少消息,所以我必须使用take和skip参数在循环中调用它,如下所示:

while (result.messages.Count == postCount)
{
    using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
    {
        using (var client = new HttpClient(handler) { BaseAddress = url, Timeout = new TimeSpan(0, 2, 0) })
        {
            cookieContainer.Add(domain, new Cookie(cookie.Name, cookie.Value));
            take = 500;
            postCount += 500;
            query["Skip"] = "0";
            query["Take"] = "0";
            builder.Query = query.ToString();
            url = builder.Uri;
            client.BaseAddress = url;
            var tempStringResult = client.GetStringAsync(url).Result; 
            skip += 500;
        }
    }
} 

问题是端点通常会抛出超时异常。所以我决定将其称为脱机(在工作者中)并缓存要在Web服务器中使用的结果。 现在问题是如何在抛出错误时重试它?通常情况下,如果我在一段时间后调用它可能会有效。

1 个答案:

答案 0 :(得分:1)

当您收到超时响应代码时,您可以减少要采用的消息数,并使用相同的skip索引重试。

东西:

var take        = 500;
var skip        = 0;
var postCount   = 0;

while(result.messages.Count == postCount)
{
    using(var handler = new HttpClientHandler { CookieContainer = cookieContainer })
    {
        using(var client = new HttpClient(handler) { BaseAddress = url, Timeout = new TimeSpan(0, 2, 0) })
        {
            cookieContainer.Add(domain, new Cookie(cookie.Name, cookie.Value));

            query["Skip"]        = skip;
            query["Take"]        = take;
            builder.Query        = query.ToString();
            url                  = builder.Uri;
            client.BaseAddress   = url;

            var response    = await client.GetAsync(url);

            if(response.IsSuccessStatusCode)
            {
                // succeeded
                skip        += take;
                postCount   += take;
            }
            else if(response.StatusCode == System.Net.HttpStatusCode.RequestTimeout)
            {
                // timeout, we reduce the number of messages to take. 
                take        -= 100;
            }
        }
    }
}