客户端打开已登录的网页(C#) (转)

像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/"); //打开浏览器  

        }  

   } 

 

原文地址:https://www.cnblogs.com/hantianwei/p/1909156.html