使用不同的代理服务器重试来自 .NET 的 HTTP 请求

Retry HTTP request from .NET with different proxy server

我可以通过 .NET 应用程序中的代理发出 HTTP 请求。我可以使用许多代理服务器,有时一个或多个会出现故障。如何让我的应用程序使用不同的代理重试 HTTP 请求?我乐于接受任何建议,并且听说过关于 Polly 增加弹性的好消息。

如果你要使用 Polly,可能是这样的:

public void CallGoogle()
{
    var proxyIndex = 0;

    var proxies = new List<IWebProxy>
    {
        new WebProxy("proxy1.test.com"),
        new WebProxy("proxy2.test.com"),
        new WebProxy("proxy3.test.com")
    };

    var policy = Policy
                 .Handle<Exception>()
                 .WaitAndRetry(new[]
                     {
                         TimeSpan.FromSeconds(1),
                         TimeSpan.FromSeconds(2),
                         TimeSpan.FromSeconds(3)
                     }, (exception, timeSpan) => proxyIndex++);

    var client = new WebClient();

    policy.Execute(() =>
    {
        client.Proxy = proxies[proxyIndex];
        client.DownloadData(new Uri("https://www.google.com"));
    });
}

对于我的用例,事实证明没有 Polly 我会过得更好。

public static string RequestWithProxies(string url, string[] proxies)
{
    var client = new WebClient
    {
        Credentials = new NetworkCredential(username, password)
    };
    var result = String.Empty;

    foreach (var proxy in proxies)
    {
        client.Proxy = new WebProxy(proxy);
        try
        {
            result = client.DownloadString(new Uri(url));
        }
        catch (Exception) { if (!String.IsNullOrEmpty(result)) break; }
    }

    if (String.IsNullOrEmpty(result)) throw new Exception($"Exhausted proxies: {String.Join(", ", proxies)}");
    return result;
}

这是一个有 Polly 的答案,但我不喜欢没有 Polly 或 Polly 等待重试的答案。

public static string RequestWithProxies(string url, string[] proxies)
{
    var client = new WebClient { Credentials = new NetworkCredential(username, password) };
    var result = String.Empty;
    var proxyIndex = 0;

    var policy = Policy.Handle<Exception>()
        .Retry(
            retryCount: proxies.Length,
            onRetry: (exception, _) => proxyIndex++);

    policy.Execute(() =>
    {
        if (proxyIndex >= proxies.Length) throw new Exception($"Exhausted proxies: {String.Join(", ", proxies)}");

        client.Proxy = new WebProxy(proxies[proxyIndex]);
        result = client.DownloadString(new Uri(url));
    });

    return result;
}