WebClient:下载未完成:远程服务器返回错误:(403)禁止.

Sha*_*k G 1 c# webclient winforms

我正在使用此代码下载文件

      private WebClient client;    
        client = new WebClient();      
        if (isBusy)
        {
            client.CancelAsync();
            isBusy = false;
            this.downloadButton.Text = "Download";
        }
        else
        {
            try {
                Uri uri = new Uri(urlTextBox.Text);
                this.downloadProgressBar.Value = 0;
                client.Headers.Add("User-Agent: Other");
                client.DownloadFileAsync(uri, "test.csv.zip");         
                this.downloadButton.Text = "Cancel";
                isBusy = true;
            }
            catch (UriFormatException ex) {
                MessageBox.Show(ex.Message);
            }
        }
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误错误

  Download Not Complete: The remote server returned an error: (403) Forbidden.
Run Code Online (Sandbox Code Playgroud)

我不知道它为什么会来.

但是当我使用uri在免费下载管理器中下载它的工作

我添加了这一行

             client.Headers.Add("User-Agent: Other");
Run Code Online (Sandbox Code Playgroud)

但它仍然无法正常工作.

如果有人能帮助我,我们将非常感激.

提前致谢.

Joh*_*mer 5

听起来你正在使用的免费下载管理器可能会欺骗引用标头,而你的实现却不是.如果将referer字段设置为特定值(即服务器上的站点),则服务器可能会限制您尝试下载的文件的下载,只能下载.你有没有尝试过:

client.Headers.Add("referer", uri);
Run Code Online (Sandbox Code Playgroud)

使用Fiddler可能值得查看下载管理器发送的请求与您的请求之间的区别,然后修改您的请求直到它工作.

编辑:

我已经测试了您提供的URL,并通过添加以下内容使其在本地工作:

client.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
client.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
Run Code Online (Sandbox Code Playgroud)

您需要提供"Accept"标头,否则服务器不知道您的客户想要/将接受什么.这是我完整的anonimized示例应用程序(为简单起见使用Sleep()):

        string url = "http://..."; // Change this to the full url of the file you want to download 
        string filename = "downloadedfile.zip"; // Change this to the filename you want to save it as locally.
        WebClient client = new WebClient(); 

        try 
        {
            Uri uri = new Uri(url);
            client.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
            client.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            client.DownloadFileAsync(uri, filename);

            while (client.IsBusy)
            {
                System.Threading.Thread.Sleep(1000);
            }
        }
        catch (UriFormatException ex) 
        {
            Console.WriteLine(ex.Message);
        }
Run Code Online (Sandbox Code Playgroud)