/// <summary> /// 加关注 /// </summary> /// <param name="web"></param> /// <param name="uid"></param> /// <returns></returns> public static string FriendCreate(WebAccessBase web, string uid) { if (web == null) { throw new ArgumentNullException("web"); } if (string.IsNullOrEmpty(uid)) { throw new ArgumentNullException("uid"); } web.Encode = Encoding.UTF8; web.Reffer = null; var home = web.GetHTML(string.Format("http://weibo.com/u/{0}", uid)); if (string.IsNullOrEmpty(home)) { return(string.Format("访问关注对象{0}页面出错", uid)); } if (home.Contains("<title>404错误</title>")) { return("工作对象被封"); } var oid = OidRegex.Match(home).Groups["oid"].Value; var location = LocationRegex.Match(home).Groups["location"].Value; var nick = NickRegex.Match(home).Groups["onick"].Value; if (string.IsNullOrEmpty(oid) || string.IsNullOrEmpty(location) || string.IsNullOrEmpty(nick)) { ComHttpWorkLogger.Info("分析关注对象{0}页面出错\r\n{1}", uid, home); return(string.Format("分析关注对象{0}页面出错", uid)); } if (uid != oid) { ComHttpWorkLogger.Info("分析关注对象{0}页面UID出错\r\n{1}", uid, home); return(string.Format("分析关注对象{0}页面UID出错", uid)); } var postUrl = string.Format("http://weibo.com/aj/f/followed?ajwvr=6&__rnd={0}", CommonExtension.GetTime()); var postData = string.Format( "uid={0}&objectid=&f=1&extra=&refer_sort=&refer_flag=&location={1}&oid={2}&wforce=1&nogroup=false&fnick={3}&_t=0", uid, location, oid, nick); var postHtml = web.PostWithHeaders(postUrl, postData, new[] { "X-Requested-With: XMLHttpRequest" }); //关注结果分析 if (string.IsNullOrEmpty(postHtml)) { return("关注失败,返回空"); } try { dynamic postResult = DynamicJson.Parse(postHtml); return(postResult.code == "100000" ? "" : string.Format("关注失败,{0}", postResult.msg)); } catch (Exception) { ComHttpWorkLogger.Info(string.Format("关注失败\r\n{0}", postHtml)); return("关注失败,分析失败"); } }
/// <summary> /// 发布文字信息与单张图片内容 /// </summary> /// <param name="login">登录信息</param> /// <param name="picPath">图片路径</param> /// <param name="msg">需要发布的文本内容</param> /// <returns></returns> public static string SendMsg(ComWeiboLogin login, string picPath, string msg) { if (Encoding.GetEncoding("GBK").GetByteCount(msg) * 2 > 280) { throw new Exception("文本内容超出280字节"); } login.Web.Encode = Encoding.UTF8; string html = login.Web.GetHTML("http://weibo.com/"); if (string.IsNullOrEmpty(html)) { ComHttpWorkLogger.Info(string.Format("微博发表失败\r\n")); return(string.Format("发表失败")); } if (picPath.Substring(picPath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower() != "jpg" && picPath.Substring(picPath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower() != "png") { throw new Exception(string.Format("图片文件扩展名错误({0})", picPath)); } var onick = onickReg.Match(html).Groups["onick"].Value; var oid = oidReg.Match(html).Groups["oid"].Value; var pic = File.ReadAllBytes(picPath); var pichtml = login.Web.UploadImage(pic, string.Format("http://picupload.service.weibo.com/interface/pic_upload.php?app=miniblog&data=1&url=weibo.com/u/{0}&markpos=1&logo=1&nick={1}&marks=1&mime=image/jpeg&ct={2}", onick, oid, new Random(Guid.NewGuid().GetHashCode()).NextDouble())) ?? ""; if (string.IsNullOrEmpty(pichtml)) { ComHttpWorkLogger.Info("图片pid获取失败\r\n{0}图片路径:\r\n{1}", pichtml, picPath); } var pid = pidReg.Match(pichtml).Groups["pid"].Value; var url = string.Format("http://weibo.com/aj/mblog/add?ajwvr=6&__rnd={0}", CommonExtension.GetTime()); var postData = string.Format("location=v6_content_home&appkey=&style_type=1&pic_id={0}&text={1}&pdetail=&rank=0&rankid=&module=stissue&pub_type=dialog&_t=0", pid, msg); var htmlMsg = login.Web.Post(url, postData); if (!string.IsNullOrEmpty(htmlMsg) && htmlMsg.Contains("\"code\":\"100000\"")) { return(""); } ComHttpWorkLogger.Info(string.Format("微博发表失败\r\n{0}", htmlMsg)); return(string.Format("发表失败")); }
/// <summary> /// 发表微博 /// </summary> /// <param name="web"></param> /// <param name="text">需要发布的文本内容</param> /// <param name="pic"></param> /// <param name="appkey"></param> /// <returns></returns> public static string AddMblog(WebAccessBase web, string text, string pic = null, string appkey = null) { if (web == null) { throw new ArgumentNullException("web"); } if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException("text", "微博内容不能为空"); } web.Encode = Encoding.UTF8; web.Reffer = new Uri("http://weibo.com/"); var url = string.Format("http://weibo.com/aj/mblog/add?ajwvr=6&__rnd={0}", CommonExtension.GetTime()); var postData = string.Format( "location=v6_content_home&appkey={2}&style_type=1&pic_id={1}&text={0}&pdetail=&rank=0&rankid=&module=stissue&pub_type=dialog&_t=0", text, pic, appkey); var htmlMsg = web.PostWithHeaders(url, postData, new[] { "X-Requested-With: XMLHttpRequest" }); if (!string.IsNullOrEmpty(htmlMsg) && htmlMsg.Contains("\"code\":\"100000\"")) { return(""); } ComHttpWorkLogger.Info(string.Format("发微博失败\r\n{0}", htmlMsg)); return(string.Format("发微博失败")); }
/// <summary> /// 发布文字信息与多张图片内容 /// </summary> /// <param name="login">登录信息</param> /// <param name="msg">信息内容</param> /// <param name="picPids">图片pid数组</param> /// <returns></returns> public static string AddMblog(ComWeiboLogin login, string msg, string picPids) { if (Encoding.GetEncoding("GBK").GetByteCount(msg) * 2 > 280) { throw new Exception("文本内容超出280字节"); } if (picPids.Split(' ').Count() > 9) { throw new Exception("图片超出9张"); } login.Web.Reffer = new Uri("http://weibo.com/"); login.Web.Encode = Encoding.UTF8; var url = string.Format("http://weibo.com/aj/mblog/add?ajwvr=6&__rnd={0}", CommonExtension.GetTime()); var postData = string.Format("location=v6_content_home&appkey=&style_type=1&pic_id={0}&text={1}&pdetail=&rank=0&rankid=&module=stissue&pub_type=dialog&_t=0", picPids, msg); var htmlMsg = login.Web.Post(url, postData); if (!string.IsNullOrEmpty(htmlMsg) && htmlMsg.Contains("\"code\":\"100000\"")) { return(""); } ComHttpWorkLogger.Info(string.Format("微博发表失败\r\n{0}", htmlMsg)); return(string.Format("发表失败")); }
/// <summary> /// 使用指定账号登录微博 /// </summary> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <param name="proxy">设置代理(可选)</param> /// <returns>WebAccessBase:</returns> public void WeiboLogin(string userName, string password, string proxy = null) { try { UserName = userName; Password = password; Error = ""; if (!string.IsNullOrEmpty(proxy)) { Web.SetProxy(proxy, "", ""); } Web.Encode = Encoding.GetEncoding("gb2312"); //todo m.weibo.cn Web.Reffer = null; Web.GetHTML("http://m.weibo.cn"); const string loginUrl = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"; Web.GetHTML(loginUrl); //编码用户名 @替换为%40 进行Base64编码 string su = userName.Replace("@", "%40"); Byte[] bufin = Encoding.UTF8.GetBytes(su); su = Convert.ToBase64String(bufin, 0, bufin.Length); var callbackStr = string.Format("jsonpcallback{0}", CommonExtension.GetTime()); var perLoginUrl = string.Format("https://login.sina.com.cn/sso/prelogin.php?checkpin=1&entry=mweibo&su={0}&callback={1}", su, callbackStr); var perLoginHtml = Web.GetHTML(perLoginUrl); if (string.IsNullOrEmpty(perLoginHtml)) { Error = string.Format("账号:{0}密码{1}访问预处理页面失败", userName, password); Result = "登录失败"; CNWeiboLoginLogger.Info(Error); return; } CaptchaResult captchaResult = null; string pcid = ""; string door = ""; string showpin = "0"; #region 打码 if (perLoginHtml.Contains("\"showpin\":1")) { showpin = "1"; var imageHtml = Web.GetHTML("https://passport.weibo.cn/captcha/image"); try { dynamic postResult = DynamicJson.Parse(imageHtml); string retcode = postResult.retcode; if (retcode != "20000000") { Error = string.Format("账号:{0}密码{1}获取验证码 错误代码:{2}错误信息:{3}", userName, password, postResult.retcode, postResult.msg); Result = "获取验证码失败"; CNWeiboLoginLogger.Info(Error); return; } pcid = postResult.data.pcid; string imageStr = postResult.data.image; imageStr = imageStr.Replace("data:image/png;base64,", ""); var imageByte = Convert.FromBase64String(imageStr); try { captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61"); } catch (Exception ex) { Error = ex.ToString(); Result = "调用打码失败"; CNWeiboLoginLogger.Error(Error, ex); return; } if (captchaResult == null) { Error = Result = "调用打码后结果为空"; CNWeiboLoginLogger.Info(Error); return; } if (!string.IsNullOrEmpty(captchaResult.Error)) { Error = Result = captchaResult.Error; CNWeiboLoginLogger.Info(Error); return; } door = captchaResult.CaptchaStr; } catch (Exception ex) { Error = ex.ToString(); Result = "执行打码失败"; CNWeiboLoginLogger.Error(Error, ex); return; } } #endregion 打码 const string postUrl = "https://passport.weibo.cn/sso/login"; //username=uwtsuy%40hyatt.altrality.com&password=TTDmtbgIYXY&savestate=1&ec=0&pagerefer=https%3A%2F%2Fpassport.weibo.cn%2Fsignin%2Fwelcome%3Fentry%3Dmweibo%26r%3Dhttp%253A%252F%252Fm.weibo.cn%252F%26&entry=mweibo&loginfrom=&client_id=&code=&hff=&hfp= string postData = string.Format( "username={0}&password={1}&savestate=1{2}&ec=0&pagerefer=https%3A%2F%2Fpassport.weibo.cn%2Fsignin%2Fwelcome%3Fentry%3Dmweibo%26r%3Dhttp%253A%252F%252Fm.weibo.cn%252F%26&entry=mweibo&loginfrom=&client_id=&code=&hff=&hfp=", userName.Replace("@", "%40"), password, showpin == "1" ? string.Format("&pincode={0}&pcid={1}", door, pcid) : ""); Web.Reffer = new Uri(loginUrl); var postHtml = Web.Post(postUrl, postData); if (string.IsNullOrEmpty(postHtml)) { Error = string.Format("账号:{0}密码{1}登录提交失败", userName, password); Result = "登录提交失败"; CNWeiboLoginLogger.Info(Error); return; } #region 设置cookies try { dynamic postResult = DynamicJson.Parse(postHtml); string retcode = postResult.retcode; if (retcode == "50011010") { Error = string.Format("账号:{0} 密码{1} 登录提交 账号有异常 错误代码:{2} 错误信息:{3}", userName, password, postResult.retcode, postResult.msg); Result = "账号有异常"; CNWeiboLoginLogger.Info(Error); return; } if (retcode == "50011002") { Error = string.Format("账号:{0} 密码{1} 登录提交 密码错误 错误代码:{2} 错误信息:{3}", userName, password, postResult.retcode, postResult.msg); Result = "密码错误"; CNWeiboLoginLogger.Info(Error); return; } if (captchaResult != null && retcode == "50011006") { try { _ruoKuaiClient.ReportError(captchaResult.Id); } catch (Exception exception) { Debug.WriteLine(exception); } Error = string.Format("账号:{0}密码{1}登录提交 错误代码:{2}错误信息:{3}", userName, password, postResult.retcode, postResult.msg); Result = "打码错误"; CNWeiboLoginLogger.Info(Error); return; } if (retcode != "20000000") { Error = string.Format("账号:{0}密码{1}登录提交 错误代码:{2}错误信息:{3}", userName, password, postResult.retcode, postResult.msg); Result = postResult.msg; CNWeiboLoginLogger.Info(Error); return; } Uid = postResult.data.uid; if (postResult.data.IsDefined("loginresulturl") && !string.IsNullOrEmpty(postResult.data["loginresulturl"])) { string loginresulturl = postResult.data["loginresulturl"] + "&savestate=1&url=http%3A%2F%2Fm.weibo.cn%2F"; Web.Reffer = new Uri(loginUrl); var temp0 = Web.GetHTML(loginresulturl); if (string.IsNullOrEmpty(temp0)) { Error = string.Format("账号{0} 密码{1} 设置weibo.cn的cookies失败", userName, password); Result = "设置cookies失败"; CNWeiboLoginLogger.Info(Error); return; } VerifyCnSecurityPage(userName, password); } else { string weibo_com = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.com"], CommonExtension.GetTime()); Web.Reffer = new Uri(loginUrl); var temp1 = Web.GetHTML(weibo_com); if (string.IsNullOrEmpty(temp1)) { Error = string.Format("账号{0}密码{1}设置weibo.com的cookies失败", userName, password); Result = "设置cookies失败"; CNWeiboLoginLogger.Info(Error); return; } string sina_com_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["sina.com.cn"], CommonExtension.GetTime()); Web.Reffer = new Uri(loginUrl); Web.GetHTML(sina_com_cn); string weibo_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.cn"], CommonExtension.GetTime()); Web.Reffer = new Uri(loginUrl); var temp2 = Web.GetHTML(weibo_cn); if (string.IsNullOrEmpty(temp2)) { Error = string.Format("账号{0}密码{1}设置weibo.cn的cookies失败", userName, password); Result = "设置cookies失败"; CNWeiboLoginLogger.Info(Error); return; } VerifyCnSecurityPage(userName, password); } } catch (Exception ex) { Error = string.Format("账号{0}密码{1}分析登录结果失败\r\n{2}", userName, password, postHtml); Result = "分析登录结果失败"; CNWeiboLoginLogger.Error(Error, ex); } #endregion 设置cookies } catch (Exception ex) { Result = Error = "发生未处理异常"; CNWeiboLoginLogger.Error(Error, ex); } }
//weibo.com解封 public string Run(WebAccessBase web) { try { web.Reffer = null; string html1 = web.GetHTML("http://weibo.com/"); if (!string.IsNullOrEmpty(html1) && html1.Contains("您当前使用的账号存在异常,请完成以下操作解除异常状态")) { #region 发短信解封 for (int m = 0; m < 10; m++) { string mobile = ""; try { mobile = smsapi.GetMobile(weibo_send_type); if (string.IsNullOrEmpty(mobile)) { //File.AppendAllText("mobile获取为空.txt", DateTime.Now + Environment.NewLine); Thread.Sleep(2000); continue; } //提交手机号到新浪 var url = "http://sass.weibo.com/aj/upside/nextstep?__rnd=" + CommonExtension.GetTime(); var postData = string.Format("mobile={0}&zone=0086&_t=0", mobile); web.Reffer = new Uri("http://sass.weibo.com/unfreeze"); var html = web.PostWithHeaders(url, postData, new[] { "X-Requested-With: XMLHttpRequest" }); if (string.IsNullOrEmpty(html)) { continue; } var temp1 = DynamicJson.Parse(html); if (temp1.code == "1000") { //发短信 html = smsapi.SendSms(mobile, weibo_send_type, "26"); if (html != "succ") { //File.AppendAllText("SendSms失败.txt", DateTime.Now + "\t" + html + "\t" + mobile + Environment.NewLine); //发生失败后,拉黑手机号,重做 //_smsapi.AddIgnoreList(mobile, _send_type); //Thread.Sleep(1000); continue; } // 收发送结果 string result = ""; int i1 = 0; while (i1 < 10) { result = smsapi.GetSmsStatus(mobile, weibo_send_type); if (result == "succ") { break; } Thread.Sleep(3000); i1++; } if (i1 >= 10) { //File.AppendAllText("一码收短信超时.txt", DateTime.Now + "\t" + mobile + Environment.NewLine); continue; } if (result == "succ") { //这里要循环检查 for (int i = 0; i < 10; i++) { Thread.Sleep(1000 * 6); url = "http://sass.weibo.com/aj/upside/check?__rnd=" + CommonExtension.GetTime(); postData = string.Format("mobile={0}&_t=0", mobile); web.Reffer = new Uri("http://sass.weibo.com/unfreeze"); html = web.PostWithHeaders(url, postData, new[] { "X-Requested-With: XMLHttpRequest" }); if (html == "{\"code\":\"1000\"}") { //成功处理 web.Reffer = new Uri("http://sass.weibo.com/unfreeze"); web.GetHTML("http://sass.weibo.com/unfreeze?step=2"); return("发短信解封成功"); } } //File.AppendAllText("发短信后检查超时.txt", DateTime.Now + "\t" + html + "\t" + mobile + Environment.NewLine); return("发短信后检查超时"); } } string message = temp1.msg; if (message.Contains("您的账号验证过于频繁") || message.Contains("系统繁忙,请稍候再试吧")) { return(message); } if (message.Contains("换个号码吧")) { Thread.Sleep(3000); } } catch (RuntimeBinderException) { } catch (Exception err) { return(err.Message); //File.AppendAllText("UnfreezeRunErr.txt", err + Environment.NewLine); } finally { if (!string.IsNullOrEmpty(mobile)) { smsapi.AddIgnoreList(mobile, weibo_send_type); } } } #endregion } else { #region 收短信解封 for (int i = 0; i < 30; i++) { string mobile = ""; try { mobile = smsapi.GetMobile(weibo_receive_type); if (mobile == "获取手机号失败") { return("获取手机号失败"); } string url1 = "http://sass.weibo.com/aj/mobile/unfreeze?__rnd=" + CommonExtension.GetTime(); string post1 = string.Format("value={0}&zone=0086&_t=0", mobile); web.Reffer = new Uri("http://sass.weibo.com/aj/quickdefreeze/mobile"); html1 = web.PostWithHeaders(url1, post1, new[] { "x-requested-with: XMLHttpRequest" }); if (string.IsNullOrEmpty(html1)) { continue; } var objectError = DynamicJson.Parse(html1); string message = objectError.msg; if (message.Contains("您的账号验证过于频繁") || message.Contains("系统繁忙,请稍候再试吧")) { return(message); } else if (message.Contains("输入的手机号码")) { continue; } else { int count = 0; //循环计数 string verified = ""; while (verified.Length != 6) //收激活码 { if (count > 10 || verified.Contains("获取验证码失败")) //工作1分钟后退出 { break; } Thread.Sleep(5000); verified = smsapi.Unlock(mobile, weibo_receive_type); count++; } if (verified.Length == 6) { string url2 = "http://sass.weibo.com/aj/user/checkstatus?__rnd=" + CommonExtension.GetTime(); string post2 = string.Format("code={0}&_t=0", verified); web.Reffer = new Uri("http://sass.weibo.com/aj/quickdefreeze/mobile"); string html2 = web.PostWithHeaders(url2, post2, new string[] { "x-requested-with: XMLHttpRequest" }); if (!string.IsNullOrEmpty(html2) && html2.Contains("100000")) { return("解封成功"); } else { //File.AppendAllText("解封失败.txt", "收短信" + html2 + "\t" + mobile + "\t" + verified + Environment.NewLine); return("解封失败"); } } } } catch (RuntimeBinderException) { } catch (Exception err) { return(err.Message); //File.AppendAllText("UnfreezeRunErr.txt", err + Environment.NewLine); } finally { if (!string.IsNullOrEmpty(mobile)) { smsapi.AddIgnoreList(mobile, weibo_receive_type); } } } #endregion } } catch (Exception e) { throw e; } return("解封超时"); }
/// <summary> /// 使用指定账号登录微博[COM] /// </summary> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <param name="proxy">设置代理(可选)</param> /// <returns>WebAccessBase:Http操作对象(存储登录结果,可供后续程序使用)</returns> public void WeiboLogin(string userName, string password, string proxy = null) { try { UserName = userName; Password = password; if (!string.IsNullOrEmpty(proxy)) { Web.SetProxy(proxy, "", ""); } Web.Encode = Encoding.GetEncoding("gb2312"); //存储访问网页后获取的源码信息 //访问weibo主页 var html = Web.GetHTML("http://weibo.com"); if (string.IsNullOrEmpty(html)) { Result = "GET新浪微博主页网络错误"; Error = string.Format("{0} {1}", Result, Web.Error.Message); ComWeiboLoginLogger.Error(Error, Web.Error); return; } #region 获取登录时的校验信息 //编码用户名 @替换为%40 进行Base64编码 string su = userName.Replace("@", "%40"); Byte[] bufin = Encoding.UTF8.GetBytes(su); su = Convert.ToBase64String(bufin, 0, bufin.Length); //拼接地址 string preLoginPageUrl = string.Format("http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su={0}&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.15)&_={1}", su, CommonExtension.GetTime().ToString(CultureInfo.InvariantCulture)); //获取校验信息 html = Web.GetHTML(preLoginPageUrl); if (string.IsNullOrEmpty(html)) { Result = "GET新浪微博prelogin页面网络错误"; Error = string.Format("{0} {1}", Result, Web.Error.Message); ComWeiboLoginLogger.Error(Error, Web.Error); return; } #endregion 获取登录时的校验信息 #region 检查并提取校验信息 string retcode = ""; string servertime; string nonce; string rsakv; string showpin; string pcid; string door = ""; CaptchaResult captchaResult = null; try { Regex rg_preloginCallBack = new Regex(@"sinaSSOController.preloginCallBack\((?<json>.*?)\)"); var json_preloginCallBack = rg_preloginCallBack.Match(html).Groups["json"].Value; dynamic preInfo = DynamicJson.Parse(json_preloginCallBack); retcode = preInfo.retcode; servertime = preInfo.servertime; nonce = preInfo.nonce; rsakv = preInfo.rsakv; showpin = preInfo.showpin; pcid = preInfo.pcid; } catch (Exception ex) { Result = "解析prelogin结果出错"; Error = string.Format("{0} {1}", Result, retcode); ComWeiboLoginLogger.Error(Error, ex); return; } #region 打码 if (showpin == "1") { string picurl = string.Format("http://login.sina.com.cn/cgi/pin.php?r={1}&s=0&p={0}", pcid, new Random(Guid.NewGuid().GetHashCode()).Next(10000000, 99999999)); Web.Reffer = new Uri("http://weibo.com/"); var imageByte = Web.GetImageByte(picurl); try { //File.WriteAllBytes("pic.jpg", imageByte); //captchaResult = CaptchaClient.Client.HandleCaptcha(imageByte); captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61"); } catch (Exception ex) { Result = "调用打码失败"; Error = string.Format("{0} {1}", Result, ex.Message); ComWeiboLoginLogger.Error(Error, ex); return; } if (captchaResult == null) { Error = Result = "调用打码后结果为空"; ComWeiboLoginLogger.Info(Error); return; } if (!string.IsNullOrEmpty(captchaResult.Error)) { Error = Result = captchaResult.Error; ComWeiboLoginLogger.Info(Error); return; } door = captchaResult.CaptchaStr; } #endregion 打码 #endregion 检查并提取校验信息 #region 生成登录信息 string sp = ""; for (int i = 0; i < 5; i++) { try { sp = SinaPassword.GetPassword(password, servertime, nonce); if (!string.IsNullOrEmpty(sp)) { Result = ""; break; } } catch (Exception ex) { Error = Result = "计算密码密文出错" + ex; } } if (string.IsNullOrEmpty(sp)) { Result = "计算密码密文失败"; ComWeiboLoginLogger.Error(Error); return; } Error = ""; int prelt = new Random(Guid.NewGuid().GetHashCode()).Next(50, 500); //entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer=&vsnf=1&su=enBtaW5keWUlNDBqb2xseS5mYW50YXN5YXBwbGUuY29t&service=miniblog&servertime=1370330588&nonce=GPDB7O&pwencode=rsa2&rsakv=1330428213&sp=51f8c7f774ff71f31e5b181df5adfadff257b4d3299ddae8f7e6c3b7656fd9604ac8796973ff314d934984b2fdd1df4636dc52a3d2ba6d575758da929c36df9761beb1820a9509a9cd35e9c467a206efab379b10803a98f626a28baec918cf35e7f1f10c463a86abdd45619a28c579088802172e30bc4ac8d4c93d24ebd7a60e&encoding=UTF-8&prelt=73&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META string postData = string.Format("entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer={6}&vsnf=1&su={0}&service=miniblog&servertime={1}&nonce={2}&pwencode=rsa2&rsakv={3}&sp={4}&sr=1440*900&encoding=UTF-8&prelt={5}&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META", su, servertime, nonce, rsakv, sp, prelt, showpin == "1" ? string.Format("&pcid={0}&door={1}", pcid, door) : ""); #endregion 生成登录信息 #region 登录新浪 Web.Reffer = new Uri("http://weibo.com/"); //登录的POST地址 string loginPostUrl = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)"; html = Web.Post(loginPostUrl, postData); if (string.IsNullOrEmpty(html)) { Result = "POST新浪微博login页面网络错误"; Error = string.Format("{0} {1}", Result, Web.Error.Message); ComWeiboLoginLogger.Error(Error, Web.Error); return; } if (html.Contains("retcode=101")) { Error = Result = "密码错误"; ComWeiboLoginLogger.Info(Error); return; } if (html.Contains("retcode=4040")) { Error = Result = "登录次数过多"; ComWeiboLoginLogger.Info(Error); return; } if (html.Contains("retcode=4057")) { Error = Result = "账号有异常"; ComWeiboLoginLogger.Info(Error); return; } if (html.Contains("retcode=4069")) { Error = Result = "账号未激活"; ComWeiboLoginLogger.Info(Error); return; } if (!html.Contains("retcode=0") && !html.Contains("retcode=4049")) { Error = string.Format("账号:{0}密码{1}登录提交失败\r\n{2}", userName, password, html); Result = "登录失败"; ComWeiboLoginLogger.Info(Error); return; } #endregion 登录新浪 #region 获取并访问设置Cookies地址 Regex regex = new Regex(@"location.replace\([""'](?<url>.*?)[""']\);"); string weiboCookieUrl = regex.Match(html).Groups["url"].Value; if (string.IsNullOrEmpty(weiboCookieUrl)) { Error = Result = "登录结果中未匹配到ajax地址"; ComWeiboLoginLogger.Info(Error); return; } string temp1 = Web.GetHTML(weiboCookieUrl); if (string.IsNullOrEmpty(temp1)) { Result = "GET新浪微博ajaxlogin页面网络错误"; Error = string.Format("{0} {1}", Result, Web.Error.Message); ComWeiboLoginLogger.Error(Error, Web.Error); return; } dynamic loginResult; if (temp1.Contains("<title>Sina Visitor System</title>")) { temp1 = "{\"result\":false,\"errno\":\"4049\",\"reason\":\"\"}"; loginResult = DynamicJson.Parse(temp1); } else { temp1 = temp1.Replace("<html><head><script language='javascript'>parent.sinaSSOController.feedBackUrlCallBack({", "{").Replace("});</script></head><body></body></html>", "}"); try { loginResult = DynamicJson.Parse(temp1); } catch (Exception ex) { Result = "反序列化出错 temp1=[" + temp1 + "]"; Error = string.Format("{0} {1}", Result, ex.Message); ComWeiboLoginLogger.Error(Error, ex); return; } } string weiboUrl = "http://weibo.com/"; if (loginResult.result) { weiboUrl += loginResult.userinfo.userdomain; } else { string errno = loginResult.errno; switch (errno) { case "5": Error = Result = "用户名错误"; return; case "101": Error = Result = "密码错误"; return; case "2070": try { if (captchaResult != null) { _ruoKuaiClient.ReportError(captchaResult.Id); } } catch (Exception) { // ignored } Error = Result = "验证码错误"; return; case "4040": Error = Result = "登录次数过于频繁"; return; case "4049": { #region 打码再登陆一次 string picurl = string.Format("http://login.sina.com.cn/cgi/pin.php?r={1}&s=0&p={0}", pcid, new Random(Guid.NewGuid().GetHashCode()).Next(10000000, 99999999)); Web.Reffer = new Uri("http://weibo.com/"); var imageByte = Web.GetImageByte(picurl); try { //File.WriteAllBytes("pic.jpg", imageByte); //captchaResult = CaptchaClient.Client.HandleCaptcha(imageByte); captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61"); } catch (Exception ex) { Result = "调用打码失败"; Error = ex.Message; return; } if (captchaResult == null) { Result = "调用打码后结果为空"; return; } if (!string.IsNullOrEmpty(captchaResult.Error)) { Result = captchaResult.Error; return; } door = captchaResult.CaptchaStr; try { sp = SinaPassword.GetPassword(password, servertime, nonce); } catch (Exception ex) { Result = "计算密码密文出错"; Error = ex.Message; return; } if (string.IsNullOrEmpty(sp)) { Result = "计算密码密文失败"; return; } prelt = new Random(Guid.NewGuid().GetHashCode()).Next(50, 500); postData = string.Format( "entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer={6}&vsnf=1&su={0}&service=miniblog&servertime={1}&nonce={2}&pwencode=rsa2&rsakv={3}&sp={4}&sr=1440*900&encoding=UTF-8&prelt={5}&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META", su, servertime, nonce, rsakv, sp, prelt, string.Format("&pcid={0}&door={1}", pcid, door)); Web.Reffer = new Uri("http://weibo.com/"); //登录的POST地址 loginPostUrl = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)"; html = Web.Post(loginPostUrl, postData); if (string.IsNullOrEmpty(html)) { Result = "POST新浪微博login页面网络错误"; Error = Web.Error.Message; return; } if (html.Contains("retcode=101")) { Result = "密码错误"; return; } if (html.Contains("retcode=4040")) { Result = "登录次数过多"; return; } if (html.Contains("retcode=4057")) { Result = "账号有异常"; return; } if (html.Contains("retcode=2070")) { try { _ruoKuaiClient.ReportError(captchaResult.Id); } catch (Exception) { // ignored } Result = "验证码错误"; return; } if (html.Contains("retcode=4069")) { Result = "账号未激活"; return; } if (!html.Contains("retcode=0")) { ComWeiboLoginLogger.Info("账号:{0}密码{1}登录提交失败\r\n{2}", userName, password, html); Result = "登录失败2"; return; } regex = new Regex(@"location.replace\([""'](?<url>.*?)[""']\);"); weiboCookieUrl = regex.Match(html).Groups["url"].Value; if (string.IsNullOrEmpty(weiboCookieUrl)) { Result = "登录结果中未匹配到ajax地址"; return; } temp1 = Web.GetHTML(weiboCookieUrl); if (string.IsNullOrEmpty(temp1)) { Result = "GET新浪微博ajaxlogin页面网络错误"; Error = Web.Error.Message; return; } temp1 = temp1.Replace( "<html><head><script language='javascript'>parent.sinaSSOController.feedBackUrlCallBack({", "{").Replace("});</script></head><body></body></html>", "}"); loginResult = DynamicJson.Parse(temp1); weiboUrl = "http://weibo.com/"; if (loginResult.result) { weiboUrl += loginResult.userinfo.userdomain; } else { errno = loginResult.errno; switch (errno) { case "5": Result = "用户名错误"; return; case "101": Result = "密码错误"; return; case "2070": try { _ruoKuaiClient.ReportError(captchaResult.Id); } catch (Exception) { // ignored } Result = "验证码错误"; return; case "4040": Result = "登录次数过于频繁"; return; case "4057": Result = "账号有异常"; return; default: Result = loginResult.reason; return; } } #endregion 打码再登陆一次 } break; case "4057": Error = Result = "账号有异常"; return; case "4069": Error = Result = "账号未激活"; return; default: Result = loginResult.reason; return; } } Web.GetHTML(weiboUrl); #endregion 获取并访问设置Cookies地址 #region 访问微博设置页面判断账号状态 html = Web.GetHTML("http://weibo.com/"); if (!string.IsNullOrEmpty(html) && html.Contains("您当前使用的账号存在异常,请完成以下操作解除异常状态")) { Error = Result = "无法收短信解封"; return; } if (!string.IsNullOrEmpty(html) && html.Contains("<title>微博帐号解冻")) { Error = Result = "封号"; return; } if (!string.IsNullOrEmpty(html) && html.Contains("<title>404错误") && html.Contains("在线申诉")) { Error = Result = "死号"; return; } html = Web.GetHTML("http://security.weibo.com/security/index"); //判断账号状态 if (!string.IsNullOrEmpty(html)) { if ((html.Contains("帐号安全系统检测到您的帐号存在高危风险"))) { Error = Result = "锁定"; return; } if (html.Contains("修改密码")) { Result = GetUidFromHTML(html) ? "正常" : "获取UID失败"; } else { //File.AppendAllText("SinaWeiboLoginUnknownError.txt", userName + "\t" + password + Environment.NewLine); ComWeiboLoginLogger.Info("账号{0}登录后安全页面分析失败\r\n{1}", userName, html); Error = Result = "未知失败"; } } else { Error = Result = "GET新浪微博账号安全页面网络错误"; } #endregion 访问微博设置页面判断账号状态 } catch (Exception ex) { Error = Result = "发生未处理异常"; ComWeiboLoginLogger.Error(Error, ex); } }
public void TestLogin() { HttpHelper hp = new HttpHelper(); HttpItem httpItem = new HttpItem { Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36", URL = "http://m.weibo.cn", //URL 必需项 Method = "GET", //URL 可选项 默认为Get Header = new WebHeaderCollection(), CookieCollection = new CookieCollection(), KeepAlive = true, AutoRedirectCookie = true, Allowautoredirect = true//是否根据301跳转 可选项 }; httpItem.Header.Add("Accept-Encoding", "gzip, deflate, sdch"); httpItem.Header.Add("Accept-Language", "zh-CN,zh;q=0.8"); var res = hp.GetHtml(httpItem); //编码用户名 @替换为%40 进行Base64编码 string su = "*****@*****.**".Replace("@", "%40"); Byte[] bufin = Encoding.UTF8.GetBytes(su); su = Convert.ToBase64String(bufin, 0, bufin.Length); var callbackStr = string.Format("jsonpcallback{0}", CommonExtension.GetTime()); var perLoginUrl = string.Format("https://login.sina.com.cn/sso/prelogin.php?checkpin=1&entry=mweibo&su={0}&callback={1}", su, callbackStr); httpItem.URL = perLoginUrl; var perLoginHtml = hp.GetHtml(httpItem); httpItem.Cookie += perLoginHtml.Cookie; string postData = string.Format( "username={0}&password={1}&savestate=1{2}&ec=0&pagerefer=https%3A%2F%2Fpassport.weibo.cn%2Fsignin%2Fwelcome%3Fentry%3Dmweibo%26r%3Dhttp%253A%252F%252Fm.weibo.cn%252F%26&entry=mweibo&loginfrom=&client_id=&code=&hff=&hfp=", "*****@*****.**".Replace("@", "%40"), "zhoulin", ""); httpItem.Referer = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"; httpItem.URL = "https://passport.weibo.cn/sso/login"; httpItem.Postdata = postData; httpItem.Method = "post"; httpItem.ContentType = "application/x-www-form-urlencoded"; var postHtml = hp.GetHtml(httpItem); dynamic postResult = DynamicJson.Parse(postHtml.Html); string retcode = postResult.retcode; string Uid = postResult.data.uid; if (postResult.data.IsDefined("loginresulturl") && !string.IsNullOrEmpty(postResult.data["loginresulturl"])) { string loginresulturl = postResult.data["loginresulturl"] + "&savestate=1&url=http%3A%2F%2Fm.weibo.cn%2F"; httpItem.Referer = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"; httpItem.URL = loginresulturl; httpItem.Method = "Get"; httpItem.ContentType = ""; var temp0 = hp.GetHtml(httpItem); } else { string weibo_com = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.com"], GetTime()); httpItem.Referer = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"; httpItem.URL = weibo_com; httpItem.Method = "Get"; httpItem.ContentType = ""; var temp1 = hp.GetHtml(httpItem); string sina_com_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["sina.com.cn"], GetTime()); httpItem.URL = weibo_com; httpItem.Method = "Get"; httpItem.ContentType = ""; var temp2 = hp.GetHtml(httpItem); string weibo_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.cn"], GetTime()); httpItem.URL = weibo_cn; httpItem.Method = "Get"; httpItem.ContentType = ""; var temp3 = hp.GetHtml(httpItem); } }