2010-07-17 174 views
9

我可以在IE下手动下载。WebClient 403禁止

http://scholar.google.com/scholar.ris?q=info:j8ymU9rzMsEJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=0

但是,使用后续代码

Web客户端的客户端=新Web客户端(); client.DownloadFile(address,filename);

显示例外: 403禁止

有什么不对? 我该怎么做?

别人

http://scholar.google.com/scholar.ris?q=info:sskrpr5jlLwJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=1

+1

我确实有403禁止在Chrome中,它可能是IE兑现你的ID和密码 – volody 2010-07-17 15:38:35

+0

@ volody:我如何在代码中执行操作? – Begtostudy 2010-07-17 15:42:29

回答

1

我得到了IE中的403,我想你需要登录才能获取资源。 您的浏览器可能拥有缓存的凭据,但您的应用没有设计用于登录。或者您是否在浏览器中登录Google - 尝试注销并查看您是否仍有权访问....

+0

http://scholar.google.com/scholar.ris?q=info:sskrpr5jlLwJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=1 但是,系统。 Net.WebException:远程服务器返回错误:(403)禁止。 – Begtostudy 2010-07-17 15:56:36

+0

我想看看这个项目http://desktopgooglereader.codeplex.com/ 看起来他们已经解决了这个问题,包括最近Google的更改 – philhobgen 2010-07-17 16:26:40

1

您需要在调用DownloadFile方法之前设置适当的http头。

WebClient webClient = new WebClient(); 
webClient.Headers.Add("???", "???"); 
webClient.Headers.Add("???", "???"); 
webClient.Headers.Add("???", "???"); 
webClient.DownloadFile(address, filename); 

要正确的值而不是这些问号可能会很棘手。您需要下载Fiddler或其他程序或网页浏览器扩展,以显示您的网页浏览器向Google发送了哪些http标题,并基本上在您的程序中复制相同的请求。

+0

http://scholar.google.com/scholar.ris ?q = info:sskrpr5jlLwJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=1 我使用了Fiddler。但有客户/ cookies /运输,应该使用? – Begtostudy 2010-07-17 16:31:12

49

只需添加一个简单的线条,你让你的下载前:

string url = ... 
string fileName = ... 

WebClient wb = new WebClient(); 
wb.Headers.Add("User-Agent: Other"); //that is the simple line! 
wb.DownloadFile(url, fileName); 

就是这样。

+0

谢谢@博格8,最好的解决方案为我工作:) – Nozim 2011-10-16 17:25:52

+0

伟大的解决方案的人。我喜欢简单。 +1,但我希望我能+2。 – 2012-06-14 10:20:09

+1

+1 - 我曾怀疑过这一点,但只是作为一个理论。令人难以置信的是,它们阻止了没有用户代理的请求。当你考虑它的时候非常聪明。 – 2013-08-09 08:36:06

0

解决这个问题的关键是通过代码执行一次请求,第二次在浏览器中,使用Fiddler记录两个请求并确保标头匹配。

我最后不得不添加标题为:

  • 接受
  • 的Accept-Encoding
  • 接受语言
  • 的User-Agent
  • 升级不安全,请

我希望这可以帮助未来的人。

1

这就是发生在我身上的事情:

我试图下载一个(公共)。xls文件(通过DownloadFile方法),可以从所有浏览器中轻松下载。

经过努力,并与所有答案奋斗(但没有运气),我终于打开堆栈,并注意到一些奇怪的东西(请参阅截图)。

虽然,该文件得到通过在浏览器HTTP下载,但它是通过DownloadFile方法给予403错误。

最后,我只是将网址从http://something更改为https://something,它工作正常。

希望这会有所帮助!

Screenshot

0

403也可以通过TLS的问题造成的。为了验证,你应该检查WebException.Response对象的文本。

 catch (WebException ex) 
    { 
     if (ex.Response != null) 
     { 
      var response = ex.Response; 
      var dataStream = response.GetResponseStream(); 
      var reader = new StreamReader(dataStream); 
      var details = reader.ReadToEnd(); 
     } 
    } 

如果是TLS,则尝试将其添加到您的代码中以强制TLS1.2。

对于.NET4:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

对于.net4.5或更高版本:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;