如何向webclient对象添加代理身份验证详细信息

时间:2012-06-27 14:39:47

标签: c# proxy webclient-download

我有一些代码会抛出407个未经授权的例外。

我正在尝试下载文件,下面是我的示例代码。我尝试过使用netcredentials和webproxy但是徒劳无功。

WebClient webClient = new WebClient();
NetworkCredential netCred=new NetworkCredential();
netCred.UserName="<<userid>>";
netCred.Password="<<password>>";
netCred.Domain="<<windowsdomainname>>";
webClient.Credentials = netCred;
WebProxy wp = new WebProxy();
wp.Credentials = netCred;
wp.Address = new Uri(@"http://proxy-xx.xxxx.co.uk:8080/proxy.pac");
webClient.Proxy = wp;
webClient.DownloadFile("http://www.win-rar.com/postdownload.html?&L=0", @"c:\winrar.exe");

2 个答案:

答案 0 :(得分:0)

在找到你的问题之前我得到了407。将您的来源修改为以下内容,这对我有用:

try
{
    var netCred = new NetworkCredential { UserName = "ununun", Password = @"pwpwpw", Domain = @"domain" };
    var webProxy = new WebProxy { Credentials = netCred };
    var webClient = new WebClient { Proxy = webProxy };
    webClient.DownloadFile(url, saveFileName);
}
catch (Exception ex)
{
    Console.WriteLine("Exception:\n{0}\n{1}", ex.Message, ex.StackTrace);
    return;
}

答案 1 :(得分:0)

这就是我昨天所做的。

WebClient client = new WebClient();
ICredentials cred;
cred = new NetworkCredential(user, password);
client.Proxy = new WebProxy("xxxx-proxy", true, null, cred);

希望有所帮助!