如何将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