C# webclient and proxy server
My solution:
WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");
If you need to authenticate to the proxy, you need to set UseDefaultCredentials
to false
, and set the proxy Credentials
.
WebProxy proxy = new WebProxy();
proxy.Address = new Uri("mywebproxyserver.com");
proxy.Credentials = new NetworkCredential("usernameHere", "pa****rdHere"); //These can be replaced by user input
proxy.UseDefaultCredentials = false;
proxy.BypassProxyOnLocal = false; //still use the proxy for local addresses
WebClient client = new WebClient();
client.Proxy = proxy;
string doc = client.DownloadString("http://www.google.com/");
If all you need is a simple proxy, you skip most of the lines above though. All you need is:
WebProxy proxy = new WebProxy("mywebproxyserver.com");
The answer proposed by Jonathan is proper, but requires that you specify the proxy credentials and url in the code. Usually, it is better to allow usage of the credentials as setup in the system by default (Users typically configure LAN Settings anyway in case they use a proxy)...
The below answer has been provided by Davide in earlier answer, but that requires modifying the app.config files. This solution is probably more useful since it does the same thing IN CODE.
In order to let the application use the default proxy settings as used in the user's system, one can use the following code:
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
wc.Proxy = wp;
This will allow the application code to use the proxy (with logged-in credentials and default proxy url settings)... No headaches! :)
Hope this helps future viewers of this page to solve their problem!
I've encountered the same issue but using a webclient for downloading a file from the internet with a Winform application the solution was adding in the app.config:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
The same solution will work for an asp.net app inserting the same rows in web.config.
Hope it will help.
You need to configure the proxy in the WebClient object.
See the WebClient.Proxy property:
http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy(VS.80).aspx