远程服务器返回错误:(401)当我尝试通过Web客户端下载文件时发生未授权错误

时间:2014-12-30 14:03:55

标签: c# authentication

我在Windows窗体应用程序中运行以下代码:

WebClient client = new WebClient();
WebProxy wp = new WebProxy("http://50.35.125.91:81/");
client.UseDefaultCredentials = true;
wp.Credentials = CredentialCache.DefaultCredentials;
wp.Credentials = new NetworkCredential("matif", "yyy", "xyz");


client.Proxy = wp;
client.DownloadFile("http://50.35.125.91:81/abc/AppUpdate.xml", @"D:\abc.xml");

每次都会出现以下异常

远程服务器返回错误:(401)未经授权。

我确信凭据有效,

3 个答案:

答案 0 :(得分:3)

为代理客户提供凭据:

using (WebClient client = new WebClient())
{
    WebProxy wp = new WebProxy("http://50.35.125.91:81/");
    wp.Credentials = new NetworkCredential("matif", "yyy", "xyz");

    client.UseDefaultCredentials = false;
    client.Credentials = wp.Credentials;
    client.Proxy = wp;
    client.DownloadFile("http://50.35.125.91:81/abc/AppUpdate.xml", @"D:\abc.xml");
}

答案 1 :(得分:1)

您正在使用默认凭据。 UseDefaultCredentials应设置为false而不是true:

client.UseDefaultCredentials = false; 

这条线你根本不需要:

wp.Credentials = CredentialCache.DefaultCredentials;

答案 2 :(得分:0)

试试这个:

using (var Client = new WebClient())
{            
   Client.Credentials = new NetworkCredential("matif", "yyy", "xyz");
   Client.DownloadFile("http://50.35.125.91:81/abc/AppUpdate.xml", @"D:\abc.xml");
}