Csharp/C#教程:WebBrowser控制会话中的下载文件分享


WebBrowser控制会话中的下载文件

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

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

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

它应该只是在WebBrowser会话中模拟cookie和标头并重新使用它们来模拟WebClient中的会话,但看起来你已经在那条路上炙手可热了。

这是我如何进行的。

  1. 从WebBrowser获取cookie和标头。

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

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

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

    标题:迭代所有收集的标题,并确保使用myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");将它们添加到web客户 myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); 例如

    Cookies:看这篇文章 。

经过一周的谷歌搜索尝试解决方案后,我发现了一个如此简单!

我是你在HTTPS URL中静默下载文件的方法,而webbrowser控件只是这样做。

1)使用webbrowser登录2)使用此代码下载。

 //build de URL string _url = "https://........." //define a download file name and location string _filename = @"C:UsersJohnDocumentssomefile.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); 

它解决了我的问题

上述就是C#学习教程:WebBrowser控制会话中的下载文件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1023793.html

(0)
上一篇 2022年1月7日
下一篇 2022年1月7日

精彩推荐