14.6. Going Through a Proxy
Problem
Many companies have a web proxy that allows employees to access the Internet, while at the same time preventing outsiders from accessing the company's internal network. The problem is that to create an application that accesses the Internet from within your company, you must first connect to your proxy and then send information through it, rather than directly out to an Internet web server.
Solution
In order to get an HttpWebRequest successfully through a specific proxy server, you need to set up a WebProxy object with the settings to validate your specific request to a given proxy. Since this function is generic for any request, you can create the AddProxyInfoToRequest method:
public static HttpWebRequest AddProxyInfoToRequest(HttpWebRequest httpRequest,
Uri proxyUri,
string proxyId,
string proxyPassword,
string proxyDomain)
{
if(httpRequest != null)
{
WebProxy proxyInfo = new WebProxy( );
proxyInfo.Address = proxyUri;
proxyInfo.BypassProxyOnLocal = true;
proxyInfo.Credentials = new NetworkCredential(proxyId,
proxyPassword,
proxyDomain);
httpRequest.Proxy = proxyInfo;
}
return httpRequest;
}If all requests are going to go through the same proxy, in the 1.x versions of the Framework, you used the static Select method on the GlobalProxySelection class to set up the proxy settings for all WebRequests. In versions after 1.x, the WebRequest.DefaultWebProxy property should be used:
Uri proxyUri = new Uri("http://webproxy:80"); WebRequest.DefaultWebProxy ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access