C#webclient和代理服务器

ant*_*009 34 c# proxy webclient

我在源代码中使用Web客户端类来使用http下载字符串.

这工作正常.但是,公司中的客户端现在都连接到代理服务器.而问题始于此.

当我测试我的应用程序时,我不认为它可以通过代理服务器,因为不断抛出的异常是"没有来自xxx.xxx.xxx.xxx的响应,这是代理服务器的IP地址.

但是,我仍然可以导航到网站URL,它在通过代理服务器连接时在浏览器中正确显示字符串,但在我使用我的Web客户端时却没有.

我必须配置Web客户端中的某些内容以允许我从代理服务器后面访问URL吗?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 42

我的解决方案

WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");
Run Code Online (Sandbox Code Playgroud)

  • 理想情况下,WebClient也应该在using语句中,因为它实现了IDisposable.虽然有用的帖子. (4认同)

Cul*_*lub 18

如果您需要验证的代理,你需要设置UseDefaultCredentialsfalse,并设置代理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/");
Run Code Online (Sandbox Code Playgroud)

如果您只需要一个简单的代理,那么您可以跳过上面的大部分内容.所有你需要的是:

WebProxy proxy = new WebProxy("mywebproxyserver.com");
Run Code Online (Sandbox Code Playgroud)


小智 9

我遇到了同样的问题,但是使用webclient从互联网上下载带有Winform应用程序的文件,解决方案是在app.config中添加的:

<system.net>
    <defaultProxy useDefaultCredentials="true" />
</system.net>
Run Code Online (Sandbox Code Playgroud)

相同的解决方案适用于在web.config中插入相同行的asp.net应用程序.

希望它会有所帮助.


Bha*_*pur 9

Jonathan提出的答案是正确的,但要求您在代码中指定代理凭据和URL.通常,最好允许在系统中默认使用凭据作为设置(用户通常在使用代理的情况下配置LAN设置)...

Davide在前面的回答中提供了以下答案,但这需要修改app.config文件.这个解决方案可能更有用,因为它在IN CODE中执行相同的操作.

为了让应用程序使用用户系统中使用的默认代理设置,可以使用以下代码:

IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials; 
wc.Proxy = wp;
Run Code Online (Sandbox Code Playgroud)

这将允许应用程序代码使用代理(具有登录凭据和默认代理URL设置)......没有头疼!:)

希望这有助于此页面的未来观众解决他们的问题!


Win*_*ith 6

您需要在WebClient对象中配置代理.

请参阅WebClient.Proxy属性:

http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy(VS.80).aspx