zoukankan      html  css  js  c++  java
  • 随手记一次利用webbowser控件打开网页后cookie读取与设置

    利用wininet.dll 组件读取cookie :

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
    private static string GetCookies(string url)
    {
    uint datasize = 1024;
    StringBuilder cookieData = new StringBuilder((int)datasize);
    if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
    {
    if (datasize < 0)
    return null;

    cookieData = new StringBuilder((int)datasize);
    if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
    return null;
    }
    return cookieData.ToString();
    }

    备注:在cookie解析的过程中:

    cookie的value中如果包含有,(逗号)的情况下,可用 %2C 替换掉

    举例:

    CookieContainer cookieContainer = new CookieContainer();
    string cookieStr = GetCookies("http://abc.com/");

    string[] cookstr = cookieStr.Split(';');
    foreach (string str in cookstr)
    {
    string[] data= str.Split('=');
    if (data[1].Trim().ToString().IndexOf(',') != -1)
    {
    data[1] = data[1].Trim().ToString().Replace(",", "%2C");
    }
    Cookie ck = new Cookie(data[0].Trim().ToString(), data[1].Trim().ToString());
    cookieContainer .Add(new Uri("http://abc.com/"), ck);
    }

     ========cookie的设置:===============================

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

    public void WebBrowserControl(string url,string cookie)
    {


    foreach (string cookieItem in cookie.Split(';'))
    {

    string[] item = cookieItem .Split('=');
    //set  cookie
    InternetSetCookie(url, item[0], item[1]);

    }

    this.webBrowser1.Url = new Uri(url);

    }

    end。

  • 相关阅读:
    python内建函数
    python中fromkeys的用法
    python中append和+号的区别
    python中input用法
    opencv3.2.0之绘图
    opencv3.2.0之Mat
    【学习】Python进行数据提取的方法总结【转载】
    【python】python中的enumerate()函数【笔记】
    【学习】如何安装GraphLab Create 【转载】
    【学习】python文件读写,用with open as的好处,非常好【转载】
  • 原文地址:https://www.cnblogs.com/luo-super/p/5692109.html
Copyright © 2011-2022 走看看