C# webclient and proxy server

ant2009 picture ant2009 · May 3, 2009 · Viewed 89.4k times · Source

I am using a web client class in my source code for downloading a string using http.

This was working fine. However, the clients in the company are all connected now to a proxy server. And the problem started from this.

When I have tested my application I don't think it can pass through the proxy server, as the exception that keeps getting thrown is "no response from xxx.xxx.xxx.xxx which is the proxy server IP address.

However, I can still navigate to the web site URL and it displays the string correctly in the browser when connecting through a proxy server, but not when I use my web client.

Is there something in the web client that I have to configure to allow me to access the url from behind a proxy server?

using (WebClient wc = new WebClient())
{
    string strURL = "http://xxxxxxxxxxxxxxxxxxxxxxxx";

    //Download only when the webclient is not busy.
    if (!wc.IsBusy)
    {
        string rtn_msg = string.Empty;
        try
        {
            rtn_msg = wc.DownloadString(new Uri(strURL));
            return rtn_msg;
        }
        catch (WebException ex)
        {
            Console.Write(ex.Message);
            return false;
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
            return false;
        }
    }
    else
    {
        System.Windows.Forms.MessageBox.Show("Busy please try again");
        return false;
    }
}

Answer

Jonathan picture Jonathan · May 28, 2012

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");