C#从HTTP文件目录下载文件,获取401错误或403错误



我正试图从本地网络设备下载几个文件:http文件目录

我想写一个代码,自动下载所有的.avi文件到我的电脑驱动器。

我有两个问题:

问题1:仅使用WebClient类进行身份验证。如果我只使用WebClient类进行连接,则会出现401未经授权的错误。

代码:

try
{
using (WebClient myWebClient = new WebClient())
{ 
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}

错误消息:身份验证失败401未授权错误

问题2:可以使用WebProxy类进行身份验证,但无法下载。Getting 403 Not found error。

代码:

try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);                   
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File "{0}" from "{1}"nn", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}

错误消息:403找不到

下载错误:System.Net.WebException:远程服务器返回错误:(404)找不到。位于System.Net.WebClient.DownloadFile(Uri地址,字符串文件名)位于System.Net.WebClient.DownloadFile(字符串地址,字符串文件名)位于C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2.Program.cs:line 139

请帮助我确定我的代码中是否有任何错误,或者是否有更好的方法提交凭据并下载所有文件。

提前感谢!

我不是Dot-Net开发人员,我只是分享我的观点。在您提到的第二点中,您得到了403,这是Acces Denied的Http状态代码。我觉得你的凭据无效,或者你没有执行操作的权限。

相关内容

最新更新