具有多个代理的HttpClient

时间:2018-09-22 06:11:15

标签: asp.net-core proxy .net-core .net-core-2.1

如何将HttpClient与多个代理一起使用?

可以通过HttpClientHandler处理单个代理:

HttpClient client1 = new HttpClient(new HttpClientHandler()
        {
            Proxy = new WebProxy()
            {
                Address = new Uri($"http://{proxyIp}:{proxyPort}"),
                BypassProxyOnLocal = false,
                UseDefaultCredentials = false
            }
        });

我希望请求能够通过多个代理。

我已经尝试像这样子化DelegatingHandler

public class ProxyDelegatingHandler : DelegatingHandler
{
    public ProxyDelegatingHandler(string proxyIp, int proxyPort):
        base(new HttpClientHandler()
        {
            Proxy = new WebProxy()
            {
                Address = new Uri($"http://{proxyIp}:{proxyPort}"),
                BypassProxyOnLocal = false,
                UseDefaultCredentials = false
            }
        })
    {        

    }

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {                            
        return base.SendAsync(request, cancellationToken);
    }
}

并将列表传递给工厂,但是会引发异常,这可能是由于ProxyDelegatingHandler的错误实现引起的:

    var handlers = new List<DelegatingHandler>();      
    handlers.Add(new ProxyDelegatingHandler(ip1, port2));
    handlers.Add(new ProxyDelegatingHandler(ip2, port2));
    HttpClient client = HttpClientFactory.Create(handlers.ToArray())
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);                        
    var res = await client.SendAsync(requestMessage);

例外:

  

“ DelegatingHandler”列表无效,因为“ CustomHandler”的属性“ InnerHandler”不为null。参数名称:处理程序

相关帖子:link

0 个答案:

没有答案