13.7. 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 a HttpWebRequest successfully through a
specific proxy server, we need to set up a
WebProxy object with the settings to validate our
specific request to a given proxy. Since this function is generic for
any request, we create the AddProxyInfoToRequest
method:
public static HttpWebRequest AddProxyInfoToRequest(HttpWebRequest httpRequest,
string proxyUri,
string proxyID,
string proxyPwd,
string proxyDomain)
{
if(httpRequest != null)
{
// create the proxy object
WebProxy proxyInfo = new WebProxy( );
// add the address of the proxy server to use
proxyInfo.Address = new Uri(proxyUri);
// tell it to bypass the proxy server for local addresses
proxyInfo.BypassProxyOnLocal = true;
// add any credential information to present to the proxy server
proxyInfo.Credentials = new NetworkCredential(proxyID,
proxyPwd,
proxyDomain);
// assign the proxy information to the request
httpRequest.Proxy = proxyInfo;
}
// return the request
return httpRequest;
}If all requests are going to go through the same proxy, you can use
the static Select method on the ...