C# Tunnel Proxy: HttpClient and HttpWebRequest

C# HttpClient and HttpWebRequest integrating 16Yun Crawler Proxy.

16Yun Engineering TeamMay 3, 20261 min read

HttpClient

C#'s HttpClient configures proxies via the WebProxy class:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
 
class Program
{
    static async Task Main()
    {
        var host = Environment.GetEnvironmentVariable("PROXY_HOST") ?? "t.16yun.cn";
        var port = Environment.GetEnvironmentVariable("PROXY_PORT") ?? "31111";
        var user = Environment.GetEnvironmentVariable("PROXY_USERNAME") ?? "user";
        var pass = Environment.GetEnvironmentVariable("PROXY_PASSWORD") ?? "password";
 
        var proxy = new WebProxy($"{host}:{port}")
        {
            Credentials = new NetworkCredential(user, pass)
        };
 
        var handler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true,
            ServerCertificateCustomValidationCallback = (_, _, _, _) => true
        };
 
        using var client = new HttpClient(handler);
        client.Timeout = TimeSpan.FromSeconds(15);
 
        var response = await client.GetStringAsync("https://httpbin.org/ip");
        Console.WriteLine(response);
    }
}

HttpWebRequest

var host = Environment.GetEnvironmentVariable("PROXY_HOST") ?? "t.16yun.cn";
var port = Environment.GetEnvironmentVariable("PROXY_PORT") ?? "31111";
var user = Environment.GetEnvironmentVariable("PROXY_USERNAME") ?? "user";
var pass = Environment.GetEnvironmentVariable("PROXY_PASSWORD") ?? "password";
 
var proxy = new WebProxy($"{host}:{port}")
{
    Credentials = new NetworkCredential(user, pass)
};
 
var request = (HttpWebRequest)WebRequest.Create("https://httpbin.org/ip");
request.Proxy = proxy;
request.Timeout = 15000;
 
using var response = (HttpWebResponse)request.GetResponse();
using var reader = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());

Four Scenarios Comparison

ScenarioHttpClientHttpWebRequest
A: Force SwitchCreate new HttpClient each timeCreate new HttpWebRequest each time
B: Keep IPReuse HttpClient instanceReuse ServicePoint
C-HTTP: Proxy-TunnelWebProxy + custom headersrequest.Headers["Proxy-Tunnel"]
C-HTTPS: Proxy-TunnelRequires custom ICertificatePolicyRequires custom auth strategy

HttpClient is recommended (modern, async, community standard). HttpWebRequest is a legacy API kept for compatibility.

Need an enterprise proxy plan?

We can tailor architecture to your target domains, concurrency, and reliability goals.