zoukankan      html  css  js  c++  java
  • 使用webBrowser下载文件

    如果直接用webBrowser.Navigate("http://***.com/");会弹出文件下载的对话框。

    而如果用webclient.UploadData()下载,对方网站是asp.net开发的话,postdata中需要有viewstate,也需要登录。

    现在的解决方法是:

    1.先使用webbrowser进行网站登录

    2.登录成功后,把webbrowser中的aspnetSessionID的cookie和DocumentText中的viewstate提取出来,并赋值给webclient

    3.使用webclient去下载文件。

    下面是第2、3步的代码

            private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                Regex reg = new Regex("<input[^<>]*id="__VIEWSTATE"[^<>]*[value="\S+"]?[^<>]*/>");
                Match m = reg.Match(webBrowser1.DocumentText);
                string viewstate = "";
    
                if (m.Success)
                {
                    reg = new Regex("value="(\S+)"");
                    m = reg.Match(m.Value);
                    if (m.Success && m.Groups.Count >= 2)
                    {
                        viewstate = HttpUtility.UrlEncode(m.Groups[1].Value);
                    }
                }
    
                string eventvalidation = "";
                reg = new Regex("<input[^<>]*id="__EVENTVALIDATION"[^<>]*[value="\S+"]?[^<>]*/>");
                m = reg.Match(webBrowser1.DocumentText);
                if (m.Success)
                {
                    reg = new Regex("value="(\S+)"");
                    m = reg.Match(m.Value);
                    if (m.Success && m.Groups.Count >= 2)
                    {
                        eventvalidation = HttpUtility.UrlEncode(m.Groups[1].Value);
                    }
                }
    
                string postdata = "EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" +
                    viewstate + "&__EVENTVALIDATION=" +
                    eventvalidation;
    
                byte[] bytearray = Encoding.UTF8.GetBytes(postdata);
    
                WebClient wc = new WebClient();
                wc.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);
                wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                wc.Headers.Add("ContentLength", bytearray.Length.ToString());
    
                byte[] bs = wc.UploadData(url, "POST", bytearray);
                string result = Encoding.UTF8.GetString(bs);
            }
  • 相关阅读:
    MySQL query_cache_type 详解
    MySQL validate_password 插件
    MySQL冷备份的跨操作系统还原
    MySQL5.7新特性笔记
    MySQL参数详解
    保存mysql用户的登录信息到~.my.cnf文件;用于方便登录操作。
    MySQL应用层传输协议分析
    python egg
    MySQL 加锁处理分析
    train_test_split, 关于随机抽样和分层抽样
  • 原文地址:https://www.cnblogs.com/xbzhu/p/7159249.html
Copyright © 2011-2022 走看看