像QQ、百度hi等等即時通訊軟體都有這種功能,就是你點選用戶端的一些按鈕,打開的網頁都是已經登入了的,因為用戶端已經登入過了,不用在網頁上重新登入一遍。
今天在百度知道上一個網友遇到這個問題,我就花時間研究一下,幫忙解決了。
用C#實作起來也比較簡單(但有一個條件,網頁登陸的時候不能有驗證碼),就是先用HttpWebRequest登陸擷取到cookie值,然後再把cookie寫到浏覽器的cookie目錄,最後再打開浏覽器。以下為實作代碼,對于有什麼問題歡迎留言。

代碼
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/"); //打開浏覽器
}
}