Description
I'm developing a web crawler framework. As usual, the web crawler needs a pool of proxies to send HTTP messages.
For example.
public async Task<string> GetRspTextByProxyAsync(IWebProxy proxy)
{
var handler = new SocketsHttpHandler()
{
UseProxy = true,
Proxy = proxy
};
using (var client = new HttpClient(handler))
{
return await client.GetStringAsync("https://github.com");//just for example
}
}As we all know, 'new HttpClient()' is not a recommended way of creating clients and it'll cause exceptions related to exhaustion of sockets while too many clients are created.
Therefore, i want to use IHttpFactory instead. But there're still some problems. As I know, DefaultHttpFactory realizes the reuse of HttpMessageHandler. But one handler must be created for one proxy. If I have thousands of proxies, it means I have to create thousands of handlers.
Also, I don't know how to use DI at this situation. I've searched StackOverFlow for solutions, like below,
services.AddHttpClient("proxy1").ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler()
{
UseProxy = true,
Proxy = new WebProxy("http://localhost", 8888)
});
services.AddHttpClient("proxy2").ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler()
{
UseProxy = true,
Proxy = new WebProxy("http://localhost", 8889)
});
services.AddHttpClient("proxy3").ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler()
{
UseProxy = true,
Proxy = new WebProxy("http://localhost", 8890)
});
services.AddHostedService<MyHostedService>();That's too ugly and I need to create clients dynamically because the amount of proxies is unknown before running. I can't write these hard codes.
What shall we do to enjoy the benefits of HttpClient(with thousands of webproxies) and avoid the side effect? I'm looking forward to suggestions and guidance.
Thank you in advance.
Activity
myFirstway commentedon Sep 23, 2019
What should I do about this?
huoshan12345 commentedon Oct 8, 2019
same issue here. Think about this case:
I have a web proxy pool and I have a thread which is adding new proxy to the pool continuously.
Now if I want to use that proxies, I have to create httpclients dynamically(get a proxy from the pool and create a httpclient with the proxy).
How to achieve this with HttpClientFactory?
myFirstway commentedon Nov 17, 2019
Now how do you solve this problem?
rynowak commentedon Nov 25, 2019
See discussion here: dotnet/extensions#521 (comment)
This is a fundamental limitation of HttpClient's design. We're going to look at a solution for this during 5.0
agertenbach commentedon Apr 21, 2020
I ran into a similar problem related to contextual application of primary handler properties at runtime. I had a robust typed HttpClient with Polly and delegating handlers chained, but some property of the primary handler needed to be different based on a runtime attribute (i.e. different certificate based on URL, endpoint, user, etc.) and trying to register a half dozen versions of the same typed client pipeline did not make sense, even if I did want to set up all the handler configurations and certs within the composition root.
I wrote a library to extend the DefaultHttpClientFactory to resolve this:
https://github.com/agertenbach/Ringleader
https://www.nuget.org/packages/Ringleader/
It takes advantage of the fact that the primary handler management and pooling uses the name of the upstream named/typed client. By wrapping the options and tacking in an IHttpMessageHandlerBuilderFilter, we can parse out the original client name to resolve the client's pipeline and options, but then create/use a more granular primary handler in the handler pool based on some provided context when the typed client is requested. The library has two interfaces that have to be implemented, one to define the typed client and the context that you'll pass in (and translate it to a string), and then a second that can use that translated string to return a well-formed primary handler when a new one is requested by the DefaultHttpClientFactory.
Hope this helps -- feedback or comments welcome.
20 remaining items
davidfowl commentedon Jun 13, 2022
Generally, setting the proxy, cookie container or client certs requires managing handler instances on your own. You can no longer follow the guidance of "use a single handler for your application" as you're now storing "per user" state on the handler instance itself.
LeaFrock commentedon Jun 16, 2022
This is true in essence. But I hope there will be some improvements here, to offload upper-level developers and help them move in the correct direction of best practices.
bugproof commentedon Jun 26, 2022
Does any workaround for this issue exist? It seems like either re-create the client before making a new request or change
WebProxyAddressproperty before next request. Is there anything wrong with the second approach?I think if I add client per proxy to
IHttpClientFactoryand change the usedHttpClientinstance when needed it will be fine.Vijay-Nirmal commentedon Jun 26, 2022
@bugproof I did a POC on using a single HttpClient instance with multiple proxy configurations in a round-robin faction, it works perfectly. But I haven't tested it in my actual application yet.
bugproof commentedon Jun 26, 2022
@Vijay-Nirmal By changing
Addressproperty or implementingIWebProxy?Vijay-Nirmal commentedon Jun 26, 2022
@bugproof Implementing
IWebProxyThe below code is just a quick POC, there might be issues in the code. Let me know if anyone knows how to improve the below code.
davidfowl commentedon Jun 26, 2022
@Vijay-Nirmal what does this accomplish? How does one set the proxy?
Vijay-Nirmal commentedon Jun 26, 2022
@davidfowl I had a background service that periodically add new proxies to the list and check for bad proxies from the list and removed them.
I need to web scrape a website which has IP based rate limiter. So, using this method, I could overcome that :)
gitlsl commentedon Sep 17, 2022
I appreciate the problem, can we add
proxy,cookietoHttpRequestMessage?Python's network request library (
requestshttpx) is very convenient. Maybe we can learn from itdavidfowl commentedon Sep 17, 2022
@gitlsl Do you have a concrete API proposal we can work through?
Do you have a direct comparison for this scenario?
gitlsl commentedon Sep 18, 2022
@davidfowl
As other mentioned above, to achieve this effect, it will cost a lot to generate a lot of connections. In fact, I have not tested it. Under this requirement, I usually use Python directly.
Here is an interesting phenomenon. You can observe that many people in this post are from the same eastern country (including me). If I remember correctly, the people who pr
sock5 proxy supportare also from this countryFor me,I wish the api looks like
https://requests.readthedocs.io/en/latest/api/header and proxyis a prop ofHttpRequestMessage,httpclientjustsend requestandconstruct responseMaybe we can maintain the compatibility of httpclient and add new feature into
https://github.com/dotnet/runtimelab/tree/feature/LLHTTP2pebezo commentedon Mar 3, 2023
With Python one can set/configure a proxy per-request at the time of request, for example:
The issue I'm hitting is that the proxy information is NOT available at app startup. It may come from the database or some other way or it should be dynamically selected. As a general rule, if something cannot be configured dynamically (i.e. via a database query later) then it is too restrictive (i.e. not usable for a class of solutions).
The other issue is an architectural one: If I have to configure the proxy in one project while the actual usage is in another one then I'm spreading the logic into multiple places. It would be a lot cleaner (for some use cases) to isolate that logic to a single place.
NCLnclNCL commentedon Nov 19, 2023
yes
vinaghost commentedon Aug 26, 2024
hi, .net is going to have version 9
any update on this issue?
dotnet/extensions#521 (comment)
wfurt commentedon Aug 26, 2024
this is not going to happen in 9.