How do I set a proxy on a HttpClientHandler?

Viewed 230

I've been trying to set a proxy on my HttpClientHandler for a while (to pass it on to a HttpClient to make requests) but nothing seems to work and the documentation I'm reading isn't helping much.

The main error I'm getting is about not being able to connect to the proxy because they're not responding (they're free, I found them online but I tried several websites and it seems odd that none of them would work for this specific reason).

Here's some of my code in Program.cs:

 private static async Task SetProxyAsync()
        {
            HttpClient httpClient = new HttpClient();
            var ip = await httpClient.GetStringAsync("https://api.ipify.org");
            Console.WriteLine($"My public IP address is: {ip}");

            HttpClientHandler handler = new HttpClientHandler();
            handler.UseProxy = true;
            handler.Proxy = new WebProxy("http://94.23.91.209:80/", true);

            HttpClient client2 = new HttpClient(handler);
            var ip2 = await client2.GetStringAsync("https://api.ipify.org");
            Console.WriteLine($"My proxy IP address is: {ip2}");
        }

I also have a Web.config file but I can't figure out if it's needed or not/what it changes to the code I have in the main program already.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.net>
        <defaultProxy>
            <proxy usesystemdefault ="false"
            proxyaddress="http://94.23.91.209:80"
            bypassonlocal="false"/>
        </defaultProxy>
    </system.net>
</configuration>

I read a bunch about the WebProxy, WebRequest and the HttpClient(Handler) classes but nothing seems to click together even after going through a lot of the documentation and a lot of other posts on here and other blogs, but I couldn't find anything that answered the kind of questions I have, so first of all thank you for reading my post and hopefully someone out there has an answer :)

0 Answers
Related