In C#, HttpClient
is a class provided by the .NET framework that enables you to send HTTP requests and receive HTTP responses. Sometimes, you may need to use a proxy server for your HTTP requests, for example, to bypass network restrictions or to hide your IP address.
To configure proxy settings for HttpClient
, you can use the HttpClientHandler
class, which provides a property called Proxy
. This property accepts an instance of the IWebProxy
interface, which you can implement or use one of the existing implementations such as WebProxy
.
Here's how to configure an HttpClient
to use a proxy server:
using System;
using System.Net;
using System.Net.Http;
public class HttpClientProxyExample
{
public static HttpClient CreateHttpClientWithProxy()
{
// Define the proxy server settings
var proxyAddress = new Uri("http://your-proxy-address:port");
var proxy = new WebProxy(proxyAddress)
{
// If your proxy requires authentication, provide the credentials
Credentials = new NetworkCredential("username", "password")
};
// Create an instance of HttpClientHandler and set the proxy
var httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true, // Ensure this is set to true
};
// Create and return the HttpClient with the handler
return new HttpClient(httpClientHandler);
}
public static async void SendRequest()
{
var httpClient = CreateHttpClientWithProxy();
try
{
// Send a GET request
HttpResponseMessage response = await httpClient.GetAsync("http://example.com");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
// Usage
class Program
{
static void Main(string[] args)
{
HttpClientProxyExample.SendRequest();
Console.ReadLine(); // Keep the console open
}
}
In this example, replace http://your-proxy-address:port
, username
, and password
with your actual proxy server's address and credentials. If your proxy does not require authentication, you can omit setting the Credentials
property.
Additionally, if you want to bypass the proxy server for local addresses, you can set the BypassProxyOnLocal
property of the WebProxy
object to true
.
proxy.BypassProxyOnLocal = true;
It's important to note that HttpClient
is intended to be instantiated once and reused throughout the life of an application. Especially in server-side applications, creating a new HttpClient
instance for each request can exhaust the number of sockets available under heavy loads. This can result in SocketException
errors.