在网上找了些代码,但模拟登录总失败,不知道是什么原因,我想实现的效果是写一个用户控件,里面进行模拟登录A站点,但页面不跳转,还是在我当前的系统里,如果我要进入A站点,直接通过地址访问A就行了,不需要再登录了,请问这样如何实现?

解决方案 »

  1.   

    本帖最后由 net_lover 于 2010-10-22 10:39:14 编辑
      

  2.   

    刚才用这个写了,但是不知道错的原因在哪里,一直就没登录成功/**//// <summary>  登录
            /// </summary>
            /// <param name="url"></param>
            /// <param name="paramList"></param>
            /// <returns></returns>
            public static string Login(String url, String paramList)
            {
                HttpWebResponse res = null;
                string strResult = "";
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.AllowAutoRedirect = false;
                    CookieContainer cookieCon = new CookieContainer();
                    req.CookieContainer = cookieCon;
                    StringBuilder UrlEncoded = new StringBuilder();
                    Char[] reserved = { '?', '=', '&' };
                    byte[] SomeBytes = null;
                    if (paramList != null)
                    {
                        int i = 0, j;
                        while (i < paramList.Length)
                        {
                            j = paramList.IndexOfAny(reserved, i);
                            if (j == -1)
                            {
                                UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));
                                break;
                            }
                            UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));
                            UrlEncoded.Append(paramList.Substring(j, 1));
                            i = j + 1;
                        }
                        SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
                        req.ContentLength = SomeBytes.Length;
                        Stream newStream = req.GetRequestStream();
                        newStream.Write(SomeBytes, 0, SomeBytes.Length);
                        newStream.Close();
                    }
                    else
                    {
                        req.ContentLength = 0;
                    }                res = (HttpWebResponse)req.GetResponse();
                    cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));
                    Stream ReceiveStream = res.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("GBK");
                    StreamReader sr = new StreamReader(ReceiveStream, encode);
                    Char[] read = new Char[256];
                    int count = sr.Read(read, 0, 256);
                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        strResult += str;
                        count = sr.Read(read, 0, 256);
                    }
                }
                catch (Exception e)
                {
                    strResult = e.ToString();
                }
                finally
                {
                    if (res != null)
                    {
                        res.Close();
                    }
                }
                return strResult;
            }
            /**//// <summary>  获取页面HTML
            /// </summary>
            /// <param name="url"></param>
            /// <param name="paramList"></param>
            /// <returns></returns>
            public static string getPage(String url, String paramList)
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Headers["If-None-Match"] = "36d0ed736e88c71:d9f";
                req.Referer = "http://website/login.do";
                CookieContainer cookieCon = new CookieContainer();
                req.CookieContainer = cookieCon;
                req.CookieContainer.SetCookies(new Uri(url), cookieheader);
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(res.GetResponseStream(),Encoding.Default);
                string strResult = sr.ReadToEnd();
                sr.Close();
                return strResult;
            }
      

  3.   

    刚找了篇文章说是没把cookie带到本地浏览器,我试试。希望大家继续解答
      

  4.   


    //模拟登录baidu
    using Zhuyi.Utility;WebUtil web = new WebUtil("https://passport.baidu.com/?login");
    string data = "username=sq_zhuyi&password=******";
    string str = web.Post(data, true);//登录成功
    using System;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Drawing;namespace Zhuyi.Utility
    {
        /// <summary>
        /// 对web请求的封装
        /// </summary>
        public class WebUtil
        {
            #region private members
            HttpWebRequest request;
            HttpWebResponse response;        Uri uri;
            Encoding encoding = Encoding.GetEncoding("gb2312");
            CookieContainer cc = new CookieContainer();
            string referer;
            byte[] data;        Stream stream;        bool hasError = false;        bool did = false;
            #endregion        public WebUtil()
            {
                uri = null;
            }
            public WebUtil(string url)
            {
                uri = new Uri(url);
            }        #region 属性
            /// <summary>
            /// 设置要请求的URL
            /// </summary>
            public string URL
            {
                set { uri = new Uri(value); }
            }
            /// <summary>
            /// 指定编码方式(默认:GB2312)
            /// </summary>
            public Encoding Encode
            {
                set { encoding = value; }
            }
            /// <summary>
            /// 设置/获取CookieContainer
            /// </summary>
            public CookieContainer Cookies
            {
                get { return cc; }
                set { cc = value; }
            }
            /// <summary>
            /// 设置请求链接源
            /// </summary>
            public string Referer
            {
                set { referer = value; }
            }
            /// <summary>
            /// 获取请求返回的cookies
            /// </summary>
            public CookieCollection GetCookies
            {
                get { return did ? cc.GetCookies(uri) : null; }
            }
            /// <summary>
            /// 获取请求返回的HTTP标头
            /// </summary>
            public WebHeaderCollection Headers
            {
                get { return did ? response.Headers : null; }
            }
            /// <summary>
            /// 是否发生错误
            /// </summary>
            public bool HasError
            {
                get { return hasError; }
            }
            #endregion        #region 提供方法
            /// <summary>
            /// GET方式发送请求
            /// </summary>
            /// <returns></returns>
            public string Get()
            {
                string msg = Send();            if (hasError) return msg;            StreamReader reader = null;
                try
                {
                    reader = new StreamReader(stream, encoding);
                    msg = reader.ReadToEnd();
                }
                catch (Exception ex)
                {
                    hasError = true;
                    msg = ex.Message;
                }
                finally
                {
                    reader.Close();
                    stream.Close();
                    response.Close();
                }
                return msg;
            }
            /// <summary>
            /// 获取图片(GET)
            /// </summary>
            /// <returns></returns>
            public Image GetImage()
            {
                string msg = Send();            if (hasError) return null;            Bitmap bitMap = null;
                try
                {
                    Image original = Image.FromStream(stream);
                    bitMap = new Bitmap(original);
                }
                catch (Exception ex)
                {
                    hasError = true;
                    msg = ex.Message;
                }
                finally
                {
                    stream.Close();
                    stream.Close();
                    response.Close();
                }
                return bitMap;
            }
            /// <summary>
            /// POST方式发送请求
            /// </summary>
            /// <param name="data">待发送数据</param>
            /// <param name="encoded">是否已进行编码</param>
            /// <returns></returns>
            public string Post(string data, bool encoded)
            {
                if (encoded) this.data = encoding.GetBytes(data);
                else this.data = encoding.GetBytes(EncodeData(data));            string msg = Send("POST");            if (hasError) return msg;            StreamReader reader = null;
                try
                {
                    reader = new StreamReader(stream, encoding);
                    msg = reader.ReadToEnd();
                }
                catch (Exception ex)
                {
                    hasError = true;
                    msg = ex.Message;
                }
                finally
                {
                    reader.Close();
                    stream.Close();
                    response.Close();
                }
                return msg;
            }
            #endregion        #region 私有方法
            private string Send()
            {
                return Send("GET");
            }
            /// <summary>
            /// 发送请求
            /// </summary>
            /// <param name="method">请求方式(GET/POST)</param>
            private string Send(string method)
            {
                if (uri == null)
                {
                    hasError = true;
                    return "URI is null";
                }
                try
                {
                    if (uri.ToString().ToLower().StartsWith("https"))
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                    }
                    System.Net.ServicePointManager.Expect100Continue = false;                request = (HttpWebRequest)WebRequest.Create(uri);                if (referer != null)
                    {
                        request.Referer = referer;
                    }
                    request.CookieContainer = cc;
                    request.KeepAlive = true;
                    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";                if (method.ToUpper() == "POST")
                    {
                        request.Method = "POST";
                        request.ContentType = "application/x-www-form-urlencoded";
                        request.ContentLength = data.Length;                    Stream newStream = request.GetRequestStream();
                        newStream.Write(data, 0, data.Length);
                        newStream.Close();
                    }                response = (HttpWebResponse)request.GetResponse();
                    if (!string.IsNullOrEmpty(response.CharacterSet))
                    {
                        try { encoding = Encoding.GetEncoding(response.CharacterSet); }
                        catch { }
                    }
                    stream = response.GetResponseStream();                hasError = false;
                    return "true";
                }
                catch (Exception ex)
                {
                    if (stream != null) stream.Close();
                    if (response != null) response.Close();
                    hasError = true;
                    return ex.Message;
                }
                finally
                {
                    did = true;
                }
            }        private string EncodeData(string data)
            {
                StringBuilder sb = new StringBuilder();
                Char[] reserved = { '=', '&' };            int i = 0, j;
                while (i < data.Length)
                {
                    j = data.IndexOfAny(reserved, i);
                    if (j == -1)
                    {
                        sb.Append(System.Web.HttpUtility.UrlEncode(data.Substring(i, data.Length - i), encoding));
                        break;
                    }
                    sb.Append(System.Web.HttpUtility.UrlEncode(data.Substring(i, j - i), encoding));
                    sb.Append(data.Substring(j, 1));
                    i = j + 1;
                }
                return sb.ToString();
            }
            //https
            private bool CheckValidationResult(object sender,
                System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                System.Security.Cryptography.X509Certificates.X509Chain chain,
                System.Net.Security.SslPolicyErrors errors)
            { // Always accept
                return true;
            }
            #endregion
        }
    }更多使用工具:
    http://download.csdn.net/source/2277988
      

  5.   

    登录成功后返回的字符串就是登录页面的HTML代码吧,但为什么我再通过地质访问该站点还是需要登录?
      

  6.   

    楼主是使用代码模拟后再打开浏览器吗?搞!!!
    模拟登录就相当于打开了一个没有窗口的浏览器,浏览器间cookie是不共享的!
    所以查看是否登录还是要用代码抓取网页判断