Proxy Configuration Examples – C#.NET

This article describes configuration of the Proxy Host for the C# .NET HTTP client. C# works well with dynamic websites.

The following configuration example code for C# .NET was provided by Michael Eisenstein:

WebProxy ProxyString = new WebProxy("http://PROXYHOST:PORT", true);
//set network credentials may be optional
NetworkCredential proxyCredential = new NetworkCredential("USERNAME", "PASSWORD");
ProxyString.Credentials = proxyCredential;
WebRequest.DefaultWebProxy =  ProxyString;
HttpWebRequest request = (HttpWebRequest);
//manually set authorization header
string authInfo = "USERNAME" + ":" + "PASSWORD";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Proxy-Authorization"] = "Basic " + authInfo;

The following section of this article presents a more complete code example.

Making Requests in C#

Below is another code sample for making HTTP requests through a proxy using C#.

string proxyUri =
string.Format("{0}:{1}", proxyAddress, proxyPort);

NetworkCredential proxyCreds = new NetworkCredential(
    proxyUserName,
    proxyPassword
);

WebProxy proxy = new WebProxy(proxyUri, true)
{
    UseDefaultCredentials = false,
    Credentials = proxyCreds,
};

HttpClient client = null;
cookieContainer = new CookieContainer();
httpClientHandler = new HttpClientHandler()
{
    Proxy = proxy,
    PreAuthenticate = true,
    UseDefaultCredentials = false,
    UseProxy = true,
    UseCookies = true,
    CookieContainer = cookieContainer
};
client = new HttpClient(httpClientHandler);

int _TimeoutSec = 90;
client.Timeout = new TimeSpan(0, 0, _TimeoutSec);
client.DefaultRequestHeaders.Add("User-Agent",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13;
    rv:55.0) Gecko/20100101 Firefox/55.0");
client.DefaultRequestHeaders.Add("Accept",
    "text/html, */*; q=0.01");
client.DefaultRequestHeaders.Add("Accept-Language",
    "gzip, deflate, br");
client.DefaultRequestHeaders.Accept.
    Add(new MediaTypeWithQualityHeaderValue
    ("application/x-www-form-urlencoded"));

try
{
    HttpResponseMessage response = await client.GetAsync(TARGETURL);
    HttpContent content = response.Content;

    // ... Check Status Code
    Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);

    // ... Read the string.
    string result = await content.ReadAsStringAsync();
}
    catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

IP Rotating Proxy Onsale

SPECIAL LIMITED TIME OFFER

00
Months
00
Days
00
Hours
00
Minutes
00
Seconds
First month free with coupon code FREE30