首页 文章

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

提问于
浏览
1

我正在尝试从本地网络设备下载多个文件:http file directory

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

我有两个问题:

问题1:仅使用WebClient类进行身份验证 . 如果我只使用WebClient类进行连接,则会收到401 Unauthorized错误 .

码:

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 Unauthorized Error

问题2:能够使用WebProxy类进行身份验证但无法下载 . 获取403未找到错误 .

码:

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}\"\n\n", 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未找到

DOWNLOAD ERROR: System.Net.WebException: The remote server returned an error: (404) Not Found. at System.Net.WebClient.DownloadFile(Uri address, String fileName) at System.Net.WebClient.DownloadFile(String address, String fileName) at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139

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

提前致谢!

1 回答

  • 0

    我不是Dot Net开发者,我只是分享我的意见 . 在第二点中,您提到您将获得403,这是Acces Denied的Http状态代码 . 我觉得您的凭据无效或您没有权限进行操作 .

相关问题