Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

C# webclient and proxy server

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...