2010-11-20 110 views
6

我正在使用WebBrowser control来浏览登录页面并下载文件。由于我无法找到自动管理下载的方法,因此我使用WebClient类尝试实现此目的。在会话中的WebBrowser控件下载文件

问题是,由于WebClient与浏览器不在同一个上下文/会话中,所以我要下载的是安全错误屏幕。

关于如何将WebBrowser会话的上下文传递给WebClient的任何想法?

+0

逾期答案以供日后参考:'URLDownloadToCacheFile' [可用于本(http://stackoverflow.com/a/19025793/1768303)。 – Noseratio 2013-09-26 10:47:06

回答

3

它应该只是模拟WebBrowser会话中的cookie和头文件,并重新使用它们来模拟WebClient中的会话,但看起来您已经很熟悉该路径。

下面是我如何继续。

  1. 从WebBrowser获取cookies和标题。

    Cookie:您可以通过处理WebBrowser控件的DocumentCompleted事件并解析来自DocumentCompleted事件的Cookie集,从WebBrowser会话中获取Cookie。

    标题:使用像Fiddler [www.fiddler2.com/]这样的代理来读取标题,以便了解服务器需要什么。

  2. 利用上面为WebClient收集的身份。

    页眉:遍历所有收集的标题,并确保他们added to the webclient使用myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");例如

    饼干:见this post

+0

我开始测试这个。这需要一点时间,但我会让你知道我是怎么走的。谢谢 – 2010-11-23 06:05:13

+0

这工作,谢谢 – 2011-03-14 00:54:20

11

经过一个星期的谷歌搜索尝试解决方案,我发现一个非常简单!

我你在HTTPS URL和webbrowser控件中静默下载文件就是这么做的。

1)使用网页浏览器登录 2)使用此代码进行下载。

//build de URL 

    string _url = "https://........." 

    //define a download file name and location 

    string _filename = @"C:\Users\John\Documents\somefile.pdf"; 

    //create a webcliente 

    WebClient cliente = new WebClient(); 

    //do some magic here (pass the webbrowser cokies to the webclient) 

    cliente.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie); 

    //and just download the file 

    cliente.DownloadFile(_urlpdf, _filename); 

它解决了我的问题

+1

谢谢!我实际上工作过。你为我节省了很多时间。 – 2014-05-15 14:16:25

+0

你让我的生活与coockies! – 2016-06-04 12:31:49