2011-11-20 98 views
1

我使用此代码下载文件Web客户端:下载未完成:远程服务器返回错误:(403)禁止。

 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); 
      } 
     } 

但我得到一个错误的错误是

Download Not Complete: The remote server returned an error: (403) Forbidden. 

我不知道为什么它是未来。

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

我加入这一行

   client.Headers.Add("User-Agent: Other"); 

但它仍然没有工作。

会有很大的升值,如果有人可以帮助我。

在此先感谢。

+0

整个列表这看起来像一个问题特定的网站,而不是C#。你可以从其他网站下载吗? –

+0

你是否通过小提琴手来运行这两个请求(工作与非工作),看看有什么不同? –

+0

我可以从网站下载文件,并通过下载管理器购买不通过此代码 –

回答

5

这听起来像你正在使用可能被欺骗的参考标头,而你的代码是不是免费的下载管理器。该服务器可能会限制你尝试下载,如果引荐字段设置为特定值(即服务器上的站点),只可下载文件的下载。你有没有尝试:

client.Headers.Add("referer", uri); 

它可能使用Fiddler看到下载管理器发送请求之间的差异是值得和你,然后修改你的,直到它的工作原理。

编辑

我测试过您提供的网址,我知道了通过添加下面的本地工作:否则

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)"); 

您需要提供一个“接受”头服务器不知道你的客户想要/会接受什么。这里是我的全anonimized示例应用程序(使用简单的睡眠()):

 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); 
     } 
+0

它仍然有相同的错误 –

+0

非常感谢你的工作 –

1

的403禁止错误,如果用户没有观看/下载特定内容的权限,通常返回。

你刚才提到,它是免费的下载管理器的工作,但你没有提到你是否提供了免费下载管理认证信息(是的,你可以做到这一点)。

无论如何,您的用户代理可能也是一个问题,有些网站不允许客户端使用未知的用户代理,请尝试添加流行的Web浏览器的auseragent,看看您是否可以下载该文件。

IE 10.6 Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0

试试这个行添加上述IE 10.6用户代理应用程序

client.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0"); 

你可以找到useragent strings on the internet

+0

我添加了行,但它仍然不工作 –

+0

你删除了这行'client.Headers.Add(“User-Agent:Other “);' – Vamsi

+0

是的,我已经删除它并将其替换为您的 –

相关问题