webBrowser登录后获取Cookie值,获取不到Cookie值,看了很久就是看不出是哪里问题。[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string cookie = "";
public Form1()
{
InitializeComponent();
}
//取当前webBrowser登录后的Cookie值
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);
//取出Cookie,当登录后才能取
private static string GetCookieString(string url)
{
// 确定cookie的大小
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
{
if (datasize < 0)
return null;
// 分配字符串生成器,大到足以容纳
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
return null;
}
return cookieData.ToString();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (GetCookieString(e.Url.ToString()) != null)
{
cookie = GetCookieString(e.Url.ToString());
}
}
catch
{
}
}
}
}
|