远程服务器返回错误:(401) 尝试通过 Web 客户端下载文件时发生未经授权的错误
本文关键字:错误 文件 下载 客户端 授权 Web 返回 服务器 | 更新日期: 2023-09-27 18:35:37
>我在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) 未经授权。
我确定凭据是有效的,
向代理和客户端提供凭据:
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");
}
您使用的是默认凭据。UseDefaultCredentials应设置为false而不是true:
client.UseDefaultCredentials = false;
还有你根本不需要的这一行:
wp.Credentials = CredentialCache.DefaultCredentials;
试试这个:
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");
}