C# HttpClient Proxy Integration
The .NET HttpClient supports proxies through HttpClientHandler and WebProxy. For production applications, IHttpClientFactory provides pooled, configurable clients with proxy support.
Basic Proxy Setup
var proxy = new WebProxy("http://gate.hexproxies.com:8080") { Credentials = new NetworkCredential("YOUR_USERNAME", "YOUR_PASSWORD") };
var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true };
var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
var response = await client.GetAsync("https://httpbin.org/ip"); var body = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Status: {response.StatusCode}"); Console.WriteLine($"Body: {body}"); ```
Sticky Sessions
var stickyProxy = new WebProxy("http://gate.hexproxies.com:8080")
{
Credentials = new NetworkCredential(
"YOUR_USERNAME-session-dotnet001",
"YOUR_PASSWORD"
)
};IHttpClientFactory with Proxy (Dependency Injection)
// In Program.cs or Startup.cs
builder.Services.AddHttpClient("proxied", client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
var proxy = new WebProxy("http://gate.hexproxies.com:8080")
{
Credentials = new NetworkCredential(
Environment.GetEnvironmentVariable("HEX_PROXY_USER"),
Environment.GetEnvironmentVariable("HEX_PROXY_PASS")
)return new HttpClientHandler { Proxy = proxy, UseProxy = true }; });
// In a service class public class ScrapingService { private readonly HttpClient _client;
public ScrapingService(IHttpClientFactory factory) { _client = factory.CreateClient("proxied"); }
public async Task<string> FetchAsync(string url) { var response = await _client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ```
Retry with Polly
using Polly;builder.Services.AddHttpClient("proxied") .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new WebProxy("http://gate.hexproxies.com:8080") { Credentials = new NetworkCredential("YOUR_USERNAME", "YOUR_PASSWORD") }, UseProxy = true }) .AddPolicyHandler( HttpPolicyExtensions .HandleTransientHttpError() .OrResult(r => r.StatusCode == (HttpStatusCode)429) .WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))) ); ```
Concurrent Requests
var urls = new[]
{
"https://httpbin.org/ip",
"https://httpbin.org/headers",
"https://httpbin.org/get"var tasks = urls.Select(async url => { var resp = await client.GetAsync(url); var body = await resp.Content.ReadAsStringAsync(); return (url, resp.StatusCode, body); });
var results = await Task.WhenAll(tasks); foreach (var (url, status, body) in results) { Console.WriteLine($"{url}: {status}"); } ```
SOCKS5 via SocketsHttpHandler (.NET 6+)
var handler = new SocketsHttpHandler
{
Proxy = new WebProxy("socks5://gate.hexproxies.com:1080")
{
Credentials = new NetworkCredential("YOUR_USERNAME", "YOUR_PASSWORD")
},
UseProxy = true
};