首页 > 解决方案 > 具有多个代理的 HttpClient

问题描述

如何使用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' 不为空。参数名称:处理程序

相关文章:链接

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

解决方案


推荐阅读