/// <summary>
        /// get prepare login status.
        /// </summary>
        /// <param name="UserName">user name</param>
        /// <returns>is success?</returns>
        private bool GetPreloginStatus(string UserName)
        {
            try
            {
                long   timestart      = TimeUtility.ConvertDateTimeInt(DateTime.Now);
                string prelogin_url   = "http://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=" + get_user(UserName) + "&rsakt=mod&client=ssologin.js(v1.4.15)&_=" + timestart;
                string Content        = HttpHelper.GetHttpContent(prelogin_url, cookies: cookies, encode: Encoding.GetEncoding("GB2312"));
                long   dateTimeEndPre = TimeUtility.ConvertDateTimeInt(DateTime.Now);

                prelt = Math.Max(dateTimeEndPre - timestart, 50).ToString();
                dynamic prepareJson = JsonConvert.DeserializeObject(Content.Split('(')[1].Split(')')[0]);

                servertime  = prepareJson.servertime;
                nonce       = prepareJson.nonce;
                weibo_rsa_n = prepareJson.pubkey;
                rsakv       = prepareJson.rsakv;
                return(true);
            }
            catch             // (Exception ex)
            {
                return(false);
            }
        }
Example #2
0
        public static HttpResult HttpRequest(string url, string postData = null, CookieContainer cookies = null, string userAgent = null, string referer = null, string cookiesDomain = null, Encoding encode = null, string method = null, IWebProxy proxy = null, string encoding = null, string contentType = null, int timeout = 8000, Dictionary <string, string> headers = null)
        {
            HttpResult httpResponse = new HttpResult();

            SeleniumDriverInfo seleniumDriverInfo = null;

            try
            {
                seleniumDriverInfo = SeleniumPool.Instance.BorrowInstance();

                // open a new tab and set the context
                ((ChromeDriver)seleniumDriverInfo.client).ExecuteScript("window.open('_blank', 'worktab');");
                seleniumDriverInfo.client.SwitchTo().Window("worktab");
                seleniumDriverInfo.client.Navigate().GoToUrl(url);
                Thread.Sleep(3000); //执行成功后仍然等待3S,用于接收后加载数据

                httpResponse.Url          = seleniumDriverInfo.client.Url;
                httpResponse.HttpCode     = 200; //todo, 根据返回的内容解析错误代码
                httpResponse.LastModified = TimeUtility.ConvertDateTimeInt(DateTime.Now);

                httpResponse.Content = seleniumDriverInfo.client.PageSource;
            }
            catch (Exception ex)
            {
                httpResponse.Url      = url;
                httpResponse.HttpCode = 500;
            }
            finally
            {
                if (seleniumDriverInfo != null)
                {
                    SeleniumPool.Instance.ReturnInstance(seleniumDriverInfo);
                }
            }

            return(httpResponse);
        }
        /// <summary>
        /// do sync check to keep alive.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SyncCheck(object sender, System.Timers.ElapsedEventArgs e)
        {
            long   timeNow = TimeUtility.ConvertDateTimeInt(DateTime.Now);
            string result  = HttpHelper.GetHttpContent(string.Format(SyncCheckUrl, timeNow + 89075, skey, wxsid, wxuin, BuildDeviceId(), synckey, timeNow), cookies: cookies, referer: WxUrl);

            //needn't do it!
            if (!result.Contains("selector:\"0\""))
            {
                string          temp   = HttpHelper.GetHttpContent(string.Format(WebWxSyncUrl, wxsid, skey, pass_ticket), cookies: cookies, referer: WxUrl);
                MatchCollection matchs = Regex.Matches(temp, @"{\s""Key"": (?<key>\d*),\s""Val"": (?<val>\d*)\s}");
                if (matchs != null && matchs.Count > 0)
                {
                    List <string> syncKeys = new List <string>();
                    foreach (Match match in matchs)
                    {
                        if (match.Success && match.Groups["Key"].Success && match.Groups["val"].Success)
                        {
                            syncKeys.Add(match.Groups["Key"].Value + "_" + match.Groups["val"].Value);
                        }
                    }
                    synckey = HttpUtility.UrlEncode(string.Join("|", syncKeys), Encoding.UTF8);
                }
            }
        }
        /// <summary>
        /// weibo login
        /// </summary>
        /// <param name="UserName">user name</param>
        /// <param name="Password">password</param>
        /// <returns>Login result</returns>
        public LoginResult DoLogin(string UserName, string Password, string UserAgent = "")
        {
            cookies = new CookieContainer();
            try
            {
                if (GetPreloginStatus(UserName))
                {
                    string login_url  = "https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=" + TimeUtility.ConvertDateTimeInt(DateTime.Now).ToString();
                    string login_data = "entry=account&gateway=1&from=&savestate=30&useticket=0&pagerefer=&vsnf=1&su=" + get_user(UserName)
                                        + "&service=sso&servertime=" + servertime + "&nonce=" + nonce + "&pwencode=rsa2&rsakv=" + rsakv + "&sp=" + get_pwa_rsa(Password)
                                        + "&sr=1440*900&encoding=UTF-8&cdult=3&domain=sina.com.cn&prelt=" + prelt + "&returntype=TEXT";

                    string  Content     = HttpHelper.GetHttpContent(login_url, login_data, cookies);
                    dynamic refreshJson = JsonConvert.DeserializeObject(Content.Substring(0, Content.LastIndexOf('}') + 1));
                    HttpHelper.GetHttpContent(refreshJson.crossDomainUrlList[0].ToString(), cookies: cookies, referer: login_url);

                    string home_url = "http://weibo.com/tnidea/";
                    string result   = HttpHelper.GetHttpContent(home_url, cookies: cookies);

                    if (string.IsNullOrWhiteSpace(result) || result.Contains("账号存在异常") || !result.Contains("$CONFIG['islogin']='******'"))
                    {
                        return(new LoginResult()
                        {
                            Result = ResultType.AccounntLimit, Msg = "Fail, Msg: Login fail! Maybe you account is disable or captcha is needed."
                        });
                    }
                }
                else
                {
                    return new LoginResult()
                           {
                               Result = ResultType.ServiceError, Msg = "Error, Msg: The method is out of date, please update!"
                           }
                };
            }
            catch (Exception e)
            {
                return(new LoginResult()
                {
                    Result = ResultType.ServiceError, Msg = "Error, Msg: " + e.ToString()
                });
            }

            LoginResult loginResult = new LoginResult()
            {
                Result = ResultType.Success, Msg = "Success", Cookies = HttpHelper.GetAllCookies(cookies)
            };

            return(loginResult);
        }
        public LoginResult DoLogin(string UserName, string Password, string UserAgent = "")
        {
            Stopwatch stopwatch = new Stopwatch();

            cookies = new CookieContainer();

            try
            {
                stopwatch.Start();
                HttpHelper.GetHttpContent("https://passport.baidu.com/passApi/html/_blank.html", cookies: cookies, cookiesDomain: "passport.baidu.com");

                //1. Get the token.
                string token_url      = string.Format("https://passport.baidu.com/v2/api/?getapi&tpl=mn&apiver=v3&tt={0}&class=login&gid={1}&logintype=dialogLogin&callback=bd__cbs__{2}", TimeUtility.ConvertDateTimeInt(DateTime.Now), Guid.NewGuid().ToString().ToUpper(), build_callback());
                string prepareContent = HttpHelper.GetHttpContent(token_url, null, cookies, referer: "https://www.baidu.com/", encode: Encoding.GetEncoding("GB2312"), cookiesDomain: "passport.baidu.com");
                //string prepareJson = prepareContent.Split('(')[1].Split(')')[0];
                dynamic prepareJson = JsonConvert.DeserializeObject(prepareContent.Split('(')[1].Split(')')[0]);
                string  token       = prepareJson.data.token;

                //2. Get public key
                string pubkey_url    = "https://passport.baidu.com/v2/getpublickey?token={0}&tpl=mn&apiver=v3&tt={1}&gid={2}&callback=bd__cbs__{3}";
                string pubkeyContent = HttpHelper.GetHttpContent(string.Format(pubkey_url, token, TimeUtility.ConvertDateTimeInt(DateTime.Now), Guid.NewGuid().ToString().ToUpper(), build_callback()), null, cookies, referer: "https://www.baidu.com/", encode: Encoding.GetEncoding("GB2312"), cookiesDomain: "passport.baidu.com");

                dynamic pubkeyJson = JsonConvert.DeserializeObject(pubkeyContent.Split('(')[1].Split(')')[0]);
                rsa_pub_baidu = pubkeyJson.pubkey;
                string KEY = pubkeyJson.key;

                stopwatch.Stop();
                //3. Build post data
                string login_data = "staticpage=https%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fv3Jump.html&charset=UTF-8&token={0}&tpl=mn&subpro=&apiver=v3&tt={1}&codestring=&safeflg=0&u=https%3A%2F%2Fwww.baidu.com%2F&isPhone=&detect=1&gid={2}&quick_user=0&logintype=dialogLogin&logLoginType=pc_loginDialog&idc=&loginmerge=true&splogin=rate&username={3}&password={4}&verifycode=&mem_pass=on&rsakey={5}&crypttype=12&ppui_logintime={6}&countrycode=&callback=parent.bd__pcbs__{7}";

                login_data = string.Format(login_data, token, TimeUtility.ConvertDateTimeInt(DateTime.Now), Guid.NewGuid().ToString().ToUpper(), HttpUtility.UrlEncode(UserName), HttpUtility.UrlEncode(get_pwa_rsa(Password)), HttpUtility.UrlEncode(KEY), stopwatch.ElapsedMilliseconds, build_callback());

                //4. Post the login data
                string login_url = "https://passport.baidu.com/v2/api/?login";
                HttpHelper.GetHttpContent(login_url, login_data, cookies, referer: "https://www.baidu.com/", cookiesDomain: "passport.baidu.com");

                string home_url = "https://www.baidu.com";
                string result   = HttpHelper.GetHttpContent(home_url, cookies: cookies, cookiesDomain: "passport.baidu.com");

                //5. Verifty the login result
                if (string.IsNullOrWhiteSpace(result) || result.Contains("账号存在异常") || !result.Contains("bds.comm.user=\""))
                {
                    return(new LoginResult()
                    {
                        Result = ResultType.AccounntLimit, Msg = "Fail, Msg: Login fail! Maybe you account is disable or captcha is needed."
                    });
                }
            }
            catch (Exception e)
            {
                return(new LoginResult()
                {
                    Result = ResultType.ServiceError, Msg = "Error, Msg: " + e.ToString()
                });
            }

            LoginResult loginResult = new LoginResult()
            {
                Result = ResultType.Success, Msg = "Success", Cookies = HttpHelper.GetAllCookies(cookies)
            };

            return(loginResult);
        }
Example #6
0
        /// <summary>
        /// 使用Http Request获取网页信息
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="postData">Post的信息</param>
        /// <param name="cookies">Cookies</param>
        /// <param name="userAgent">浏览器标识</param>
        /// <param name="referer">来源页</param>
        /// <param name="cookiesDomain">Cookies的Domian参数,配合cookies使用;为空则取url的Host</param>
        /// <param name="encode">编码方式,用于解析html</param>
        /// <param name="method">提交方式,例如POST或GET,默认通过postData是否为空判断</param>
        /// <param name="proxy"></param>
        /// <param name="encoding"></param>
        /// <param name="contentType"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static HttpResult HttpRequest(string url, string postData = null, CookieContainer cookies = null, string userAgent = null, string referer = null, string cookiesDomain = null, Encoding encode = null, string method = null, IWebProxy proxy = null, string encoding = null, string contentType = null, int timeout = 8000, Dictionary <string, string> headers = null)
        {
            HttpResult httpResponse = new HttpResult();

            try
            {
                HttpWebResponse httpWebResponse = null;
                if (!string.IsNullOrEmpty(postData) || (!string.IsNullOrEmpty(method) && method.ToUpper() == "POST"))
                {
                    httpWebResponse = CreatePostHttpResponse(url, postData, timeout, userAgent, cookies, referer, proxy, contentType, headers);
                }
                else
                {
                    httpWebResponse = CreateGetHttpResponse(url, timeout, userAgent, cookies, referer, proxy, contentType, headers);
                }

                httpResponse.Url          = httpWebResponse.ResponseUri.ToString();
                httpResponse.HttpCode     = (int)httpWebResponse.StatusCode;
                httpResponse.LastModified = TimeUtility.ConvertDateTimeInt(httpWebResponse.LastModified);

                string Content = null;
                //头部预读取缓冲区,字节形式
                var bytes = new List <byte>();
                //头部预读取缓冲区,字符串
                String cache = string.Empty;

                //创建流对象并解码
                Stream ResponseStream;
                switch (httpWebResponse.ContentEncoding.ToUpperInvariant())
                {
                case "GZIP":
                    ResponseStream = new GZipStream(
                        httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;

                case "DEFLATE":
                    ResponseStream = new DeflateStream(
                        httpWebResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;

                default:
                    ResponseStream = httpWebResponse.GetResponseStream();
                    break;
                }

                try
                {
                    while (true)
                    {
                        var b = ResponseStream.ReadByte();
                        if (b < 0) //end of stream
                        {
                            break;
                        }
                        bytes.Add((byte)b);

                        if (!cache.EndsWith("</head>", StringComparison.OrdinalIgnoreCase))
                        {
                            cache += (char)b;
                        }
                    }

                    string Ncharset = "";
                    string Hcharset = "";
                    string Rcharset = "";

                    //1,使用解析ContentType,解析Html编码声明,自动编码识别三种来猜测编码,选取任意两者相同的编码
                    if (encode == null)
                    {
                        Match match = Regex.Match(cache, CharsetReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        if (match.Success)
                        {
                            Rcharset = match.Groups["Charset"].Value;
                        }

                        try
                        {
                            string text = "";
                            if (!string.IsNullOrEmpty(text = httpWebResponse.ContentType))
                            {
                                text = text.ToLower(CultureInfo.InvariantCulture);
                                string[] array  = text.Split(new char[] { ';', '=', ' ' });
                                bool     flag   = false;
                                string[] array2 = array;
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    string text2 = array2[i];
                                    if (text2 == "charset")
                                    {
                                        flag = true;
                                    }
                                    else
                                    {
                                        if (flag)
                                        {
                                            Hcharset = text2;
                                        }
                                    }
                                }
                            }
                        }
                        catch { }

                        if (!string.IsNullOrEmpty(Rcharset) && !string.IsNullOrEmpty(Hcharset) && Hcharset.ToUpper() == Rcharset.ToUpper())
                        {
                            encode = Encoding.GetEncoding(Hcharset);
                        }
                        else
                        {
                            Ncharset = NChardetHelper.RecogCharset(bytes.ToArray(), Language.CHINESE, -1);

                            if (!string.IsNullOrEmpty(Ncharset) && (Ncharset.ToUpper() == Rcharset.ToUpper() || Ncharset.ToUpper() == Hcharset.ToUpper()))
                            {
                                encode = Encoding.GetEncoding(Ncharset);
                            }
                        }
                    }

                    //2,使用人工标注的编码
                    if (encode == null && !string.IsNullOrEmpty(encoding))
                    {
                        try
                        {
                            encode = Encoding.GetEncoding(encoding);
                        }
                        catch { }
                    }

                    //3,使用单一方式识别出的编码,网页自动识别 > 解析ContentType > 解析Html编码声明
                    if (encode == null && !string.IsNullOrEmpty(Ncharset))
                    {
                        encode = Encoding.GetEncoding(Ncharset);
                    }
                    if (encode == null && !string.IsNullOrEmpty(Hcharset))
                    {
                        encode = Encoding.GetEncoding(Hcharset);
                    }
                    if (encode == null && !string.IsNullOrEmpty(Rcharset))
                    {
                        encode = Encoding.GetEncoding(Rcharset);
                    }

                    //4,使用默认编码,听天由命吧
                    if (encode == null)
                    {
                        encode = Encoding.Default;
                    }

                    Content = encode.GetString(bytes.ToArray());
                    ResponseStream.Close();
                }
                catch (Exception ex)
                {
                    httpResponse.Content = ex.ToString();
                    return(httpResponse);
                }
                finally
                {
                    httpWebResponse.Close();
                }

                //get the Cookies,support httponly.
                if (string.IsNullOrEmpty(cookiesDomain))
                {
                    cookiesDomain = httpWebResponse.ResponseUri.Host;
                }

                cookies = new CookieContainer();
                CookieCollection httpHeaderCookies = SetCookie(httpWebResponse, cookiesDomain);
                cookies.Add(httpHeaderCookies ?? httpWebResponse.Cookies);

                httpResponse.Content = Content;
            }
            catch (Exception ex)
            {
                httpResponse.Content  = ex.ToString();
                httpResponse.HttpCode = DetermineResultStatus(ex);
            }
            return(httpResponse);
        }
        /// <summary>
        /// Needn't provide username and password. You can put any string for those.
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public LoginResult DoLogin(string UserName, string Password, string UserAgent = "")
        {
            LoginResult loginResult = new LoginResult();

            HttpHelper.GetHttpContent("https://wx.qq.com/?&lang=zh_CN", cookies: cookies);

            //request the image, and send this image url to email.
            string QRLogin = HttpHelper.GetHttpContent("https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=" + TimeUtility.ConvertDateTimeInt(DateTime.Now), cookies: cookies);

            string QRUid = "";
            string qrUrl = "";
            Match  m     = Regex.Match(QRLogin, "\"(?<QRUid>.*?)\";");

            if (m.Success && m.Groups["QRUid"].Success)
            {
                QRUid = m.Groups["QRUid"].Value;
                qrUrl = string.Format(QRUrlFmt, QRUid);
            }

            //send QR image to other process.
            string qrResult = PluginHelper.Operation(LoginSite.WeChat.ToString(), qrUrl, null);

            if (!string.IsNullOrEmpty(qrResult))
            {
                string strFmt = "https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&r={1}8&_={2}";

                int i = 0;
                do
                {
                    string result = HttpHelper.GetHttpContent(string.Format(strFmt, QRUid, "-595416181", TimeUtility.ConvertDateTimeInt(DateTime.Now)), cookies: cookies);

                    i++;

                    //If contains window.code=200, succ; If contains window.code=201, ready。
                    if (result.Contains("window.code=200;"))
                    {
                        Match m2 = Regex.Match(result, "redirect_uri=\"(?<redirect>.*?)\";");
                        if (m2.Success && m2.Groups["redirect"].Success)
                        {
                            string redirectContent = HttpHelper.GetHttpContent(m2.Groups["redirect"].Value + "&fun=new&version=v2&lang=zh_CN", cookies: cookies, referer: WxUrl);
                            Match  m3 = Regex.Match(redirectContent, "<skey>(?<skey>.*?)</skey><wxsid>(?<wxsid>.*?)</wxsid><wxuin>(?<wxuin>.*?)</wxuin><pass_ticket>(?<pass_ticket>.*?)</pass_ticket>");
                            if (m3.Success && m3.Groups["skey"].Success && m3.Groups["wxsid"].Success && m3.Groups["wxuin"].Success && m3.Groups["pass_ticket"].Success)
                            {
                                skey        = m3.Groups["skey"].Value;
                                wxsid       = m3.Groups["wxsid"].Value;
                                wxuin       = m3.Groups["wxuin"].Value;
                                pass_ticket = m3.Groups["pass_ticket"].Value;

                                //wxInit, Get the synckey.
                                string wxInitUrl  = string.Format("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r={0}&lang=zh_CN&pass_ticket={1}", TimeUtility.ConvertDateTimeInt(DateTime.Now) / 1000, pass_ticket);
                                string wxInitPost = "{\"BaseRequest\":{\"Uin\":\"" + wxuin + "\",\"Sid\":\"" + wxsid + "\",\"Skey\":\"" + skey + "\",\"DeviceID\":\"" + BuildDeviceId() + "\"}}";
                                do
                                {
                                    string wxInitContent = HttpHelper.GetHttpContent(wxInitUrl, wxInitPost, cookies, referer: "https://wx.qq.com/?&lang=zh_CN");
                                    if (!string.IsNullOrEmpty(wxInitContent))
                                    {
                                        synckey = GetSyncKeyStr(wxInitContent);
                                        if (!string.IsNullOrEmpty(synckey))
                                        {
                                            break;
                                        }
                                    }
                                }while (true);


                                tickTimer.Interval = 2000;
                                tickTimer.Elapsed += new System.Timers.ElapsedEventHandler(SyncCheck);
                                tickTimer.Start();

                                loginResult.Result  = ResultType.Success;
                                loginResult.Msg     = "Success";
                                loginResult.Cookies = HttpHelper.GetAllCookies(cookies);
                                return(loginResult);
                            }
                        }
                    }
                }while (i <= 20);
            }

            loginResult.Result = ResultType.Timeout;
            loginResult.Msg    = "error, no body scan the QR code in limited time.";

            return(loginResult);
        }