Going Through a Proxy

Going Through a Proxy


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.


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,
	                          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,
	        // 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, 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 Version 2.0, the WebRequest.Default-WebProxy property should be used:

	Uri proxyUri = new Uri("http://webproxy:80");
	WebRequest.DefaultWebProxy = new WebProxy(proxyURI);

	// Old v1.x way of doing this…
	//GlobalProxySelection.Select = new WebProxy(proxyURI);


AddProxyInfoToRequest takes the URI of the proxy and creates a Uri object, which is used to construct the WebProxy object. The WebProxy object is set to bypass the proxy for local addresses and then the credential information is used to create a NetworkCredential object. The NetworkCredential object represents the authentication information necessary for the request to succeed at this proxy and is assigned to the WebProxy.Credentials property. Once the WebProxy object is completed, it is assigned to the Proxy property of the HttpWebRequest and the request is ready to be submitted.

See Also

See the "WebProxy Class," "NetworkCredential Class," and "HttpWebRequest Class" topics in the MSDN documentation.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows