1

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

4

3 回答 3

3

如果你要使用 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"));
    });
}
于 2018-07-09T15:56:40.643 回答
0

对于我的用例,事实证明,如果没有 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;
}
于 2018-07-11T02:34:10.203 回答
0

这是波莉的答案,但我不喜欢没有波莉或波莉等待重试的答案。

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;
}
于 2018-07-11T02:37:36.767 回答