System.Net.WebRequest

If you need your application to access the internet, but you are behind a proxy server or want to change the way pages you request are cached, this is the article for you!
Email Image
kick it on DotNetKicks.com
About System.Net.WebRequest

The System.Net.WebRequest class handles any HTTP or HTTPS requests that your application makes. By default, it uses the Internet Explorer proxy settings and will used a cached copy of a page (subject to the age of the page) instead of requesting the page from the server.

If you find you need to change the caching policy or configure a proxy manually, you will need to use the following code:

Firstly lets add the using statements for the namespaces that contain the classes we need to use.

using System.Net;
using System.Net.Cache;

If you are behind a proxy server, configure the proxy details first.

/* Instantiate a WebProxy object and configure it with the server's IP Address.
You can specify a port for the proxy server by putting :8080 or whatever the port number is at the end of the IP address. e.g. 192.168.1.10:8080 */

WebProxy proxy = new WebProxy("192.168.1.10");

/* If your Proxy server requires authentication, set the credentials you want to use to authenticate. */
proxy.Credentials = new NetworkCredential("User", "Password", "Domain");

If you want to modify the Caching policy, then you need to set the DefaultCachePolicy property.

/* Set the DefaultCachePolicy for WebRequests.
In this example I have chosen to bypass the cache so every request goes directly to the source page, however this can be changed by choosing a different RequestCacheLevel. */

WebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

If you configured a WebProxy, set it as the default proxy to be used by the WebRequest class.

// Set the proxy used by the WebRequest class.
WebRequest.DefaultWebProxy = proxy;

This article was published on the 24th December 2007