C#模拟登录主动推送信息

请求https接口时注意设置 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

/// <summary>
        /// 获取token,保存cookie
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <param name="objCookieContainer"></param>
        /// <returns></returns>
        public string Login(string username, string pwd, ref CookieContainer objCookieContainer)
        {
            string uriStr = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
            string pwdMd5 = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5");
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("username", username);//	15	
            postData.Add("pwd", pwdMd5);//	15	
            postData.Add("imgcode", "");
            postData.Add("f", "json");
            string jsonArray = RequestUrl(uriStr, postData, ref objCookieContainer);
            string token = Regex.Match(jsonArray, @"([\d]{7,11})", RegexOptions.IgnoreCase).Value;
            return token;
        }
        /// <summary>
        /// 获取Fakeid
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <param name="objCookieContainer"></param>
        /// <returns></returns>
        public string GetFakeid(string token, ref CookieContainer objCookieContainer)
        {
            Dictionary<string, string> postData = new Dictionary<string, string>();
            string urirStr = "https://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&token=" + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0&groupid=0";
            string jsone = RequestUrl(urirStr, postData, ref objCookieContainer);
            string fakeidlist = Regex.Match(jsone, "<script id=\"json-friendList\" type=\"json/text\">([\\s\\S]*?)</script>", RegexOptions.IgnoreCase).Value;
            MatchCollection mc = Regex.Matches(fakeidlist, "([\\d]{7,11})");
            string[] fakeid = new string[mc.Count];
            for (int i = 0; i < mc.Count; i++)
            {
                fakeid[i] = mc[i].Value;
            }
            return fakeid[0];
        }
        /// <summary>
        /// 获取粉丝的相关信息
        /// </summary>
        /// <param name="Fakeid"></param>
        /// <param name="objCookieContainer"></param>
        /// <returns></returns>
        public string[] GetUserInfoByFakeid(string token, string Fakeid, ref CookieContainer objCookieContainer)
        {
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("token", token);
            postData.Add("ajax", "1");
            string strUrl = "https://mp.weixin.qq.com/cgi-bin/getcontactinfo?t=ajax-getcontactinfo&lang=zh_CN&fakeid=" + Fakeid;
            string fakeid = RequestUrl(strUrl, postData, ref objCookieContainer);
            //string fakeid = Regex.Match(jsonArray, "<script id=\"json-friendList\" type=\"json/text\">([\\s\\S]*?)</script>", RegexOptions.IgnoreCase).Value;
            JObject jo = JObject.Parse(fakeid);
            return jo.Properties().Select(item => item.Value.ToString()).ToArray();
        }
        public void SendMessage(string token, string toFakeid, string content, ref CookieContainer objCookieContainer)
        {
            string strUrl = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN";
            Dictionary<string, string> postData = new Dictionary<string, string>();
            postData.Add("type", "1");
            postData.Add("content", content);
            postData.Add("error", "false");
            postData.Add("tofakeid", toFakeid);
            postData.Add("token", token);
            postData.Add("ajax", "1");
            RequestUrl(strUrl, postData, ref objCookieContainer);
        }
  
        /// <summary>
        /// post模拟登录
        /// </summary>
        /// <param name="strUrl"></param>
        /// <param name="postData"></param>
        /// <param name="objCookieContainer"></param>
        /// <returns></returns>
        public static string RequestUrl(string strUrl, Dictionary<string, string> postData, ref CookieContainer objCookieContainer)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
            req.Method = "POST";
            req.KeepAlive = true;
            req.ContentType = "	application/x-www-form-urlencoded; charset=UTF-8";
            req.Referer = strUrl.Remove(strUrl.LastIndexOf("/"));//,,.Substring(;
            // req.Timeout = 10000;
            if (objCookieContainer == null)
                objCookieContainer = new CookieContainer();
            req.CookieContainer = objCookieContainer;
            req.ContentLength = 0;
            System.Text.RegularExpressions.Regex _reg = new System.Text.RegularExpressions.Regex("^https://",
                   System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (_reg.IsMatch(strUrl))
            {
               ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
               ServicePointManager.ServerCertificateValidationCallback =new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
            }
            if (postData != null && postData.Count > 0)
            {
                StringBuilder objEncodedPostDatas = new StringBuilder();
                foreach (KeyValuePair<string, string> kv in postData)
                {
                    objEncodedPostDatas.Append(HttpUtility.UrlEncode(kv.Key));
                    objEncodedPostDatas.Append("=");
                    objEncodedPostDatas.Append(HttpUtility.UrlEncode(kv.Value));
                    objEncodedPostDatas.Append("&");
                }
                byte[] byteData = Encoding.UTF8.GetBytes(objEncodedPostDatas.ToString().TrimEnd('&'));
                req.ContentLength = byteData.Length;
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(byteData, 0, byteData.Length);
                req.CookieContainer.GetCookies(req.RequestUri);
                // reqStream.Close();
            }
            string strResponse = "";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            objCookieContainer = req.CookieContainer;
            Stream resStream = res.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, Encoding.UTF8);//.UTF8))
            strResponse = sr.ReadToEnd();
            // res.Close();
            return strResponse;
        }
         public static bool CheckValidationResult(object sender,
                                      System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                      System.Security.Cryptography.X509Certificates.X509Chain chain,
                                      System.Net.Security.SslPolicyErrors errors)
         {
             //直接确认,不然打不开  
             return true;
         }

 

 

posted @ 2013-07-10 12:42  lampon  阅读(496)  评论(0编辑  收藏  举报