之所以写这个,是因为本来想写一个Youtube刷评论的工具,把登录做出来了,后面就没继续做下去。

涉及到基本的HttpWatch的应用以及Fiddler的应用(Fd主要用来排查问题,通过对比 浏览器和vs代码 找出问题所在!以浏览器为标准)。

通过HttpWatch抓包分析,我把登录Youtube一共分为三个阶段:

1. 请求 打开录入邮箱地址 页面

2. 请求 回发本邮箱地址,加载邮箱账号 头像

3. 请求 回发本邮箱地址和密码, 登录Youtube

有很多的Cookie和PostData的话是 服务器不做校验的,也就是说重要的 Cookie和Post/Get数据并不是全部你所看到的,这个你可以后期 模拟登陆成功之后,逐个删掉测试看是否还能登陆成功 来判断 该参数是否必须!

上面的原理其实在做其他 网站的模拟 登录 中也是一样的。

大家直接看代码吧。

 private void button1_Click(object sender, EventArgs e)
         {
             var cookieJar = new CookieContainer();
             CookieAwareWebClient webClient = new CookieAwareWebClient(cookieJar);

             string GAPS = string.Empty;
             string GALX = string.Empty;
             string GoogleAccountsLocale_session = string.Empty;

             string NID = string.Empty;
             string ProfileInformation = string.Empty; 

             //1.第一部分init
             string url1 = "https://accounts.google.com/ServiceLogin?sacu=1&continue=https%3A%2F%2F"
             +"www.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26feature%3Dsign_in_button%26next%3D%252Fwatch%253Fv%253DpMUv7qmKQik%26hl%3Dzh-CN&hl=zh-CN&service=youtube";//地址  

             string srcString1 = webClient.DownloadString(url1);//解码  

             //receive cookie
              GAPS = GetCookie("GAPS", cookieJar);
              GALX = GetCookie("GALX", cookieJar);
              GoogleAccountsLocale_session = GetCookie("GoogleAccountsLocale_session", cookieJar);

             //2.第二部分input email
             webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
             string postString2 = "_utf8=☃" + "&bgresponse="
                 + "&checkConnection=youtube:724:0" + "&checkedDomains=youtube" + "&continue=https://www.youtube.com/signin?action_handle_signin=true&app=desktop&feature=sign_in_button&next=%2Fwatch%3Fv%3DpMUv7qmKQik&hl=zh-CN"
                 + "&dnConn=" + "&Email=【此处填写自己的Gmail邮箱】" + "&GALX=" + GALX + "&gxf=AFoagUVXYmSP1FoIo4SFJlAauKdrDab_0A:1465396649942"
                 + "&hl=zh-CN" + "&Page=PasswordSeparationSignIn" + "&ProfileInformation=" + "&pstMsg=1" + "&sacu=1"
                 + "&service=youtube" + "&signIn=下一步";

             byte[] postData2 = Encoding.UTF8.GetBytes(postString2);//编码,尤其是汉字,事先要看下抓取网页的编码方式
             string url2 = "https://accounts.google.com/AccountLoginInfo";//地址  

             webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
             byte[] responseData2 = webClient.UploadData(url2, "POST", postData2);//得到返回字符流
             string srcString2 = Encoding.UTF8.GetString(responseData2);//解码  

             GAPS = GetCookie("GAPS", cookieJar);

            //本文地址:http://www.cnblogs.com/x-poior/p/5585506.html 转载请注明,谢谢!

             //3.第三部分input pw
            //   webClient.Headers.Add("Referer", "https://accounts.google.com/AccountLoginInfo");
            //   ProfileInformation = QuMiddle(srcString2, @"name=""ProfileInformation"" type=""hidden"" value=""", @""">"); 后面排除法得出结论,该参数不是必需的,

             string postString3 = "_utf8=☃" + "&bgresponse="
                 + "&checkConnection=youtube:724:0" + "&checkConnection=youtube:398:0"
                 + "&checkedDomains=youtube" + "&checkedDomains=youtube"
                 + "&continue=https://www.youtube.com/signin?action_handle_signin=true&app=desktop&feature=sign_in_button&next=%2Fwatch%3Fv%3DpMUv7qmKQik&hl=zh-CN"
                 + "&dnConn=" + "&Email=【此处填写自己的Gmail邮箱】" + "&GALX=" + GALX + "&gxf=AFoagUVXYmSP1FoIo4SFJlAauKdrDab_0A:1465396649942"
                 + "&hl=zh-CN" + "&Page=PasswordSeparationSignIn" + "&Passwd=【此处填写自己的Gmail密码】"
                 + "&PersistentCookie=yes" + "&ProfileInformation=" + "&pstMsg=1" + "&pstMsg=1"
                 + "&rmShown=1" + "&sacu=1"
                 + "&service=youtube" + "&signIn=登录";

             byte[] postData3 = Encoding.UTF8.GetBytes(postString3);//编码,尤其是汉字,事先要看下抓取网页的编码方式
             string url3 = "https://accounts.google.com/ServiceLoginAuth";//地址  

             webClient.Method = "POST";
             string srcString3 = webClient.UploadString(url3, postString3);

             //第四部分,校验Cookie数目判断是否成功!
             var lastCookie = cookieJar;//注意,如果第三部分,返回的Response的Cookie的数量有>20 个的话,说明登陆成功了!Google 返回给你很多凭证,可以登录Google大部分的产品、
             var s2s4 = srcString3;

             var agereg = webClient.DownloadString("https://www.youtube.com/watch?v=VYwkmp97-B4");//左边是受年龄限制的视频,不登陆验证是没法观看下载的!!返回Html-String里含有“ytplayer.config”说明可以观看下载!

         }

其他的几个帮助方法,帮助类。

/// <summary>
        /// 获取Cookie的值
        /// </summary>
        /// <param name="cookieName">Cookie名称</param>
        /// <param name="cc">Cookie集合对象</param>
        /// <returns>返回Cookie名称对应值</returns>
        public static string GetCookie(string cookieName, CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c1 in colCookies) lstCookies.Add(c1);
            }
            var model = lstCookies.Find(p => p.Name == cookieName);
            if (model != null)
            {
                return model.Value;
            }
            return string.Empty;
        }
     //本文地址:http://www.cnblogs.com/x-poior/p/5585506.html 转载请注明,谢谢!
 || leftlocation > rightlocation)//判断右边字符串是否存在于总字符串中,左边字符串位置是否在右边字符串前  { return ""; } strmidlength = rightlocation - leftlocation;//计算中间字符串长度  strmid = str.Substring(leftlocation, strmidlength);//取出中间字符串  return strmid;//返回中间字符串  }

CookieAwareWebClient .cs

     public class CookieAwareWebClient : WebClient
     {
         public string Method;
         public CookieContainer CookieContainer { get; set; }
         public Uri Uri { get; set; }

         public CookieAwareWebClient()
             : this(new CookieContainer())
         {
         }

         public CookieAwareWebClient(CookieContainer cookies)
         {
             this.CookieContainer = cookies;
             this.Encoding = Encoding.UTF8;
         }

         protected override WebRequest GetWebRequest(Uri address)
         {
             WebRequest request = base.GetWebRequest(address);
             if (request is HttpWebRequest)
             {
                 (request as HttpWebRequest).CookieContainer = this.CookieContainer;
                 (request as HttpWebRequest).ServicePoint.Expect100Continue = false;
                 (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.5 Safari/537.36";
                 (request as HttpWebRequest).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                 (request as HttpWebRequest).Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en;q=0.6,nl;q=0.4,zh-TW;q=0.2");
                 (request as HttpWebRequest).Referer = "";
                 (request as HttpWebRequest).KeepAlive = true;
                 (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                 if (Method == "POST")
                 {
                     (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";
                 }
             }
             HttpWebRequest httpRequest = (HttpWebRequest)request;
             httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
             return httpRequest;
         }

         protected override WebResponse GetWebResponse(WebRequest request)
         {
             WebResponse response = base.GetWebResponse(request);
             String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

             if (setCookieHeader != null)
             {
                 //do something if needed to parse out the cookie.
                 try
                 {
                     if (setCookieHeader != null)
                     {
                         Cookie cookie = new Cookie();
                         cookie.Domain = request.RequestUri.Host;
                         this.CookieContainer.Add(cookie);
                     }
                 }
                 catch (Exception)
                 {

                 }
             }
             return response;
         }
     }

本文地址:http://www.cnblogs.com/x-poior/p/5585506.html 转载请注明,谢谢!

2016C#模拟谷歌Google登陆Gmail&Youtube小案例的更多相关文章

  1. 谷歌google搜索打不开、谷歌gmail邮箱及相关服务无法登录的解决的方法

    歌打不开 google打不开,与中国大陆封杀有关,可是主要是由于近期googleserver在全球范围内又一次进行了布局调整. 解决的方法是仅仅要改动用户本地计算机hosts文件就能够了. 一.Win ...

  2. 谷歌上不去,长期的解决方案。在稳定高速Google和Gmail

    对稳定Google神器 国内Google很不稳定,缓慢并经常上不去,由"我想去Google",安全和稳定的使用Google.Gmail.Google+所以通常需要特殊的手段岗位胜任 ...

  3. 谷歌上不去了,长久解决方式。能够稳定高速上Google和Gmail

    稳定上Google的神器 国内Google很不稳定.速度慢且常常上不去,通过"我要上Google".能够安全稳定地使用Google.Gmail.Google+等平时须要特殊手段才干 ...

  4. 谷歌 google

    google Google是搜索引擎名,也是一家美国上市公司名称.Google公司于1998年9月7日以私有股份公司的形式创立,以设计并管理一个互联网的搜索引擎.Google公司的总部称作“Googl ...

  5. 经典面试题(二)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯

    1.正整数序列Q中的每个元素都至少能被正整数a和b中的一个整除,现给定a和b,需要计算出Q中的前几项, 例如,当a=3,b=5,N=6时,序列为3,5,6,9,10,12 (1).设计一个函数void ...

  6. 《java入门第一季》之类小案例(模拟用户登录)

    首先是做一个用户登录的小案例.在此基础上加入其它逻辑. import java.util.Scanner; /* * 模拟登录,给三次机会,并提示还有几次.如果登录成功,就可以玩猜数字小游戏了. * ...

  7. 使用selenium和phantomJS浏览器登陆豆瓣的小演示

    # 使用selenium和phantomJS浏览器登陆豆瓣的小演示 # 导入库 from selenium import webdriver # 实例化一个浏览器对象 web = webdriver. ...

  8. [PHP自动化-进阶]004.Snoopy VS CURL 模拟Discuz.net登陆

    引言:采集论坛第一步就是要模拟登陆,由于各个站点登录表单各不相同,验证方式又是多种多样,所以直接提交用户名密码到登录页面就比较繁琐. 所以我们采用cookie来模拟登陆无疑是最佳捷径. 今天我们要处理 ...

  9. Google Meet & gmail & video conference

    Google Meet & gmail & video conference Conv-2019 & live stream Google Meet https://meet. ...

随机推荐

  1. python数据结构之二叉树遍历的实现

    本篇是实现二叉树的三种遍历,先序遍历,中序遍历,后序遍历 #!/usr/bin/python # -*- coding: utf-8 -*- class TreeNode(object): def _ ...

  2. Asp.net中的ajax回调模式(ICallbackEventHandler)

    客户端回调本质上就是指通过前端的客户端脚本向服务器端传递相应的数据参数,服务器端再以接受到的参数进行查询和处理,最后将结果回传到客户端进行显示.asp.net 2.0提供了实现无刷新回调的接口ICal ...

  3. adb使用

    一.使用adb删除系统应用,如Launcher.apk adb root                 获取root权限 adb remount          挂载系统的读写权限 adb she ...

  4. swift 如何删除subviews

    scrollView.subviews.map { (var view) -> () in if (view is UIButton) { view.removeFromSuperview() ...

  5. searchableselect不支持onchange的问题

    1.找到jquery.searchableSelect.js 2.找到selectItem函数 修改里面的方法,加入自定义你要回调的函数 selectItem: function(item){ //L ...

  6. sql 字符次数

    FParentPath 查询字段 本条语句 条件是 ,  查询 , 在这个字段出现了几次 1=没有 2=1次 3=2次(依次累加)

  7. 查询反模式 - GroupBy、HAVING的理解

    为了最简单地说明问题,我特地设计了一张这样的表. 一.GROUP BY单值规则 规则1:单值规则,跟在SELECT后面的列表,对于每个分组来说,必须返回且仅仅返回一个值. 典型的表现就是跟在SELEC ...

  8. Visual Studio快捷键 [VS2008/VS2005]快捷键

    VS系统通用快捷键: 1.自动排版(类似VC6中的Alt+F8) 编辑.格式化选定内容 Ctrl + K,Ctrl + F 根据周围的代码行,正确缩进选定的代码行. 2.注释与去掉注释功能. 编辑.注 ...

  9. sqlite3基础

    要使用sqlite,首先需要添加库文件libsqlite3.dylib.当你搜索libsqlite3关键字时,会发现还有一个libsqlite3.0.dylib的库文件,这里还是建议添加libsqli ...

  10. MMO之禅(二)职业精神

    MMO之禅(二)职业精神 --心态 目标 信仰 Zephyr 201304 继续上篇,继续讲什么?打了很多腹稿点滴,从引擎架构,到上层数据.逻辑模块规划,想了很多,临起笔,却总发觉四顾心茫然,乱不可言 ...