webBrowser获取完整cookie,并把cookie传给httpHelper源码
看了苏飞老大的教程,弄了个实例。。分享下。。嘿嘿 俺是菜鸟,代码写的垃圾。。能看懂就好。。
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using DotNet.Utilities;
namespace webBrowser获取完整cookie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
HttpHelper http = new HttpHelper();
HttpItem item = null;
string cookie = "";
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("http://www.baidu.com/");
}
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text.Trim();
if (str.ToLower().Contains("https://") || str.ToLower().Contains("http://"))
{
webBrowser1.Url = new Uri(textBox1.Text.Trim());
}
else
{
webBrowser1.Url = new Uri("http://" + textBox1.Text.Trim());
}
}
private void button2_Click(object sender, EventArgs e)
{
//把webBrowser1登陆的cookie传给HttpHelper
item = new HttpItem()
{
URL = webBrowser1.Url.AbsoluteUri,//URL
Method = "Get",//URL 可选项 默认为Get
Cookie = cookie,//调用webBrowser1登陆的cookie
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
};
HttpResult result = http.GetHtml(item);
string html = result.Html;
richTextBox1.AppendText(html + "\r\n\r\n");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
cookie=GetCookieString(e.Url.ToString());
richTextBox1.Text=cookie;
}
catch
{
}
}
//取当前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)
{
// Determine the size of the cookie
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
return null;
}
return cookieData.ToString();
}
}
}
工程源码下载:
|