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);
            }
  • 相关阅读:
    Xcode9学习笔记74
    Xcode9学习笔记73
    Xcode9学习笔记72
    Xcode9学习笔记71
    【Finish】Python Day 8
    【Finish】Python Day 7
    【Finish】Python Day 6
    【Finish】Python Day 5
    【Finish】Python Day 4
    【Finish】Python Day 3
  • 原文地址:https://www.cnblogs.com/xbzhu/p/7159249.html
Copyright © 2011-2022 走看看