客户端打开已登录的网页(C#) (转)
时间:2010-12-17 来源:韩天伟
代码
using System.IO;
using System.Text;
using System.Net;
using System.Runtime.InteropServices;
class Login
{
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
public static void Main()
{
CookieCollection myCookies = new CookieCollection(); //cookie集合
byte[] data = Encoding.ASCII.GetBytes("username=XXXXXX&password=********"); //用户名、密码信息
string url = @"http://www.XXX.com/……"; //登陆表单的action地址
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
myRequest.CookieContainer = new CookieContainer();
try
{
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
}
catch (WebException)
{
throw new WebException("网络链接错误!");
}
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
myCookies.Add(myResponse.Cookies); //添加cookie
foreach (Cookie cookie in myCookies) //将cookie设置为浏览的cookie
{
InternetSetCookie(
"http://" + cookie.Domain.ToString(),
cookie.Name.ToString(),
cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");
}
System.Diagnostics.Process.Start("http://www.XXX.com/"); //打开浏览器
}
}











