2010-11-20 75 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