通過winform+模擬登錄實現快速一鍵登錄到人才招聘網站

来源:http://www.cnblogs.com/zuowj/archive/2017/05/15/6855610.html
-Advertisement-
Play Games

之前為了便於人事部門招聘登錄網站更簡潔高效,免去每天頻繁輸網址、用戶名、密碼等相關登錄信息,特基於winform+HttpWebRequest實現模擬請求登錄,最終達到一鍵登錄到招聘網站後臺的效果。 要實現一鍵登錄到各大人才招聘網站就必需先瞭解網站的登錄步驟即原理,然後通過代碼一步步模擬實現即可。 ...


之前為了便於人事部門招聘登錄網站更簡潔高效,免去每天頻繁輸網址、用戶名、密碼等相關登錄信息,特基於winform+HttpWebRequest實現模擬請求登錄,最終達到一鍵登錄到招聘網站後臺的效果。

要實現一鍵登錄到各大人才招聘網站就必需先瞭解網站的登錄步驟即原理,然後通過代碼一步步模擬實現即可。

通過我對前程無憂、中國人才熱線、中華英才網 三個網站的登錄研究,找出基本相同的以下幾個步聚:

1.請求登錄主頁面,然後獲取隱藏域的欄位信息;

2.構建登錄請求數據,有的網站是form表單請求,有的網站是:json請求

3.請求後獲取到登錄的Cookie,然後通過設置IE的Cookie,最後打開IE瀏覽器及指定的管理後臺地址即可。

除了上述三大步驟以外,其實還涉及一個重要的知識點,那就是:C#調用javascript腳本並獲得執行的結果,因為各網站中有用到js生成的加密數據,而這些js加密方法我們無法直接聯想到對應的c#方法,故必需採用js方法獲取加密數據,這個在本文後面我會講解幾種方法。

上面已經分析了一鍵登錄到人才招聘網站的原理,下麵就分別貼出:前程無憂、中國人才熱線、 這二個網站的登錄實現代碼,並作簡要說明,以便大家學習與參考:

(PS:註意實現一鍵登錄只是為了便於人事提高網站的使用效率,請不要利用我的代碼作非法的事情,否則後果自負,同時也不排除後續這些網站會改變登錄方式,那麼這些登錄就都會失效的)

登錄中國人才熱線:HttpLoginCjolHelper

    public class HttpLoginCjolHelper
    {
        private static readonly CodeDomProvider _provider = new Microsoft.JScript.JScriptCodeProvider();
        private CookieContainer cjolCookies = new CookieContainer();


        public string Login(string loginName, string loginPassword)
        {

            string validateCode, codekey;

            validateCode = GetValidateCode(out codekey);

            if (string.IsNullOrEmpty(validateCode)) return null;

            var rs = HttpPost("http://newrms.cjol.com/Account/HrLogin", new Dictionary<string, object> { 
            { "r_u_name", loginName }, { "r_p_word", loginPassword }, 
            { "r_v_code", validateCode },{ "r_v_codekey", codekey }
            });

            string newUrl = rs.Headers["Location"].ToString();
            if (newUrl.IndexOf("/Default") < 0 && newUrl.IndexOf("message") > 0)
            {
                string pattren = "(?<=message=).+$";
                var regx = new System.Text.RegularExpressions.Regex(pattren);
                string errMsg = regx.Match(newUrl).Value;
                return Uri.UnescapeDataString(errMsg);
            }

            //if (!newUrl.StartsWith("http://" + rs.ResponseUri.Host))
            //{
            //    newUrl = string.Format("http://{0}{1}", rs.ResponseUri.Host, newUrl);
            //}

            newUrl = "http://newrms.cjol.com/searchengine";

            //var jr = GetResponseContent(rs);

            BaseUtil.OpenAdminPage(cjolCookies, new Uri(newUrl));
            return null;
        }


        private HttpWebResponse HttpPost(string url, Dictionary<string, object> postData)
        {
            string desKey = "!@#$%26)(*&^cjol<16>:|}{=-/*-+.CJOL@*&^%*()*<299>";
            string logindataVal = HttpLoginCjolHelper.JScriptRun("jsencrypt", desKey, JsonConvert.SerializeObject(postData)).ToString(); //DesEncrypt(desKey, JsonConvert.SerializeObject(postData));
            string postDataContent = "logindata=" + logindataVal;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] data = Encoding.UTF8.GetBytes(postDataContent);
            request.ContentLength = data.Length;
            request.AllowAutoRedirect = false;
            request.CookieContainer = cjolCookies;
            //request.Accept = "application/json";
            request.Referer = "http://www.cjol.com/hr/";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(data, 0, data.Length);
            myRequestStream.Close();
            myRequestStream = null;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            return response;
        }

        private string GetResponseContent(HttpWebResponse response)
        {
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        private string GetValidateCode(out string codekey)
        {
            codekey = null;
            string validateCode = null;
            string validateCodeKey = null;
            var codeForm = new FrmValidateCode();
            codeForm.ChangeValidateCode += (btn, args) =>
            {
                validateCodeKey = Guid.NewGuid().ToString().ToLower();
                string codeimgUrl = "http://newrms.cjol.com/Common/ValidateCodePicture?Key=1&guid=" + validateCodeKey;
                args.Data[0] = codeimgUrl;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(codeimgUrl);
                request.Method = "GET";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
                request.CookieContainer = cjolCookies;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                var codePic = new Bitmap(myResponseStream);
                (args.Data[1] as PictureBox).Image = codePic;
                myResponseStream.Close();
                myResponseStream = null;

            };

            codeForm.EnterValidateCode += (btn, args) =>
            {
                validateCode = args.Data[0].ToString();
                if (!CheckValidateCode(validateCode))
                {
                    args.Data[1] = "驗證碼校驗失敗!";
                }
            };

            if (codeForm.ShowDialog() == DialogResult.OK)
            {
                codekey = validateCodeKey;
                return validateCode;
            }

            return null;
        }

        private bool CheckValidateCode(string code)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://newrms.cjol.com/Account/Verification?txtValidateCode=" + code + "&rid=" + Guid.NewGuid().ToString("N"));
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
            request.Host = "newrms.cjol.com";
            request.Referer = "http://www.cjol.com/hr/";
            request.CookieContainer = cjolCookies;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string rs = GetResponseContent(response);
            if (rs.Contains("(true)"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static object JScriptRun(string jsMethodName, params object[] jsParams)
        {
            //編譯的參數  
            var compiler = _provider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            CompilerResults results = compiler.CompileAssemblyFromSource(parameters, jScriptClass);
            Assembly assembly = results.CompiledAssembly;

            //動態編譯腳本中的內容  
            Type _evaluateType = assembly.GetType("kyecjol.jsClass");

            //執行指定的方法並傳參數  
            object retObj = _evaluateType.InvokeMember(jsMethodName, BindingFlags.InvokeMethod,
                        null, null, jsParams);
            return retObj;
        }


        private const string jScriptClass = @"
        package kyecjol {
        
            public class jsClass {

            public static function jsencrypt(k,e) {
                var t = e.replace(/\\0/g, '')
                    ,n = stringToHex(des(k, t, 1, 0));
                    //,n=stringToHex(k+e);
                return n;
            }

            
            public static function des(e, t, n, r,i) {
            var s = 'charCodeAt', o = 'fromCharCode', u = new Array(16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756), a = new Array(-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-134217728,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-134217728,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-134217728,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-134217728,-2146435040,-2146402272,1081344), f = new Array(520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584), l = new Array(8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928), c = new Array(256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080), h = new Array(536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312), p = new Array(2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154), d = new Array(268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696), v = des_createKeys(e), m = 0, g, y, b, w, E, S, x, T, N, C, k, L, A, O, M, _ = t.length, D = 0, P = v.length == 32 ? 3 : 9;
            P == 3 ? N = n ? new Array(0,32,2) : new Array(30,-2,-2) : N = n ? new Array(0,32,2,62,30,-2,64,96,2) : new Array(94,62,-2,32,64,2,30,-2,-2),
            t += '\0\0\0\0\0\0\0\0';
            var result = '',
            tempresult = '';

            r == 1 && (C = i[s](m++) << 24 | i[s](m++) << 16 | i[s](m++) << 8 | i[s](m++),
            L = i[s](m++) << 24 | i[s](m++) << 16 | i[s](m++) << 8 | i[s](m++),
            m = 0);

            while (m < _) {
                n ? (x = t[s](m++) << 16 | t[s](m++),
                T = t[s](m++) << 16 | t[s](m++)) : (x = t[s](m++) << 24 | t[s](m++) << 16 | t[s](m++) << 8 | t[s](m++),
                T = t[s](m++) << 24 | t[s](m++) << 16 | t[s](m++) << 8 | t[s](m++)),
                r == 1 && (n ? (x ^= C,
                T ^= L) : (k = C,
                A = L,
                C = x,
                L = T)),
                b = (x >>> 4 ^ T) & 252645135,
                T ^= b,
                x ^= b << 4,
                b = (x >>> 16 ^ T) & 65535,
                T ^= b,
                x ^= b << 16,
                b = (T >>> 2 ^ x) & 858993459,
                x ^= b,
                T ^= b << 2,
                b = (T >>> 8 ^ x) & 16711935,
                x ^= b,
                T ^= b << 8,
                b = (x >>> 1 ^ T) & 1431655765,
                T ^= b,
                x ^= b << 1,
                x = x << 1 | x >>> 31,
                T = T << 1 | T >>> 31;
                for (var y = 0; y < P; y += 3) {
                    O = N[y + 1],
                    M = N[y + 2];
                    for (g = N[y]; g != O; g += M)
                        E = T ^ v[g],
                        S = (T >>> 4 | T << 28) ^ v[g + 1],
                        b = x,
                        x = T,
                        T = b ^ (a[E >>> 24 & 63] | l[E >>> 16 & 63] | h[E >>> 8 & 63] | d[E & 63] | u[S >>> 24 & 63] | f[S >>> 16 & 63] | c[S >>> 8 & 63] | p[S & 63]);
                    b = x,
                    x = T,
                    T = b;
                }
                x = x >>> 1 | x << 31,
                T = T >>> 1 | T << 31,
                b = (x >>> 1 ^ T) & 1431655765,
                T ^= b,
                x ^= b << 1,
                b = (T >>> 8 ^ x) & 16711935,
                x ^= b,
                T ^= b << 8,
                b = (T >>> 2 ^ x) & 858993459,
                x ^= b,
                T ^= b << 2,
                b = (x >>> 16 ^ T) & 65535,
                T ^= b,
                x ^= b << 16,
                b = (x >>> 4 ^ T) & 252645135,
                T ^= b,
                x ^= b << 4,
                r == 1 && (n ? (C = x,
                L = T) : (x ^= k,
                T ^= A)),
                n ? tempresult += String[o](x >>> 24, x >>> 16 & 255, x >>> 8 & 255, x & 255, T >>> 24, T >>> 16 & 255, T >>> 8 & 255, T & 255) : tempresult += String[o](x >>> 16 & 65535, x & 65535, T >>> 16 & 65535, T & 65535),
                n ? D += 16 : D += 8,
                D == 512 && (result += tempresult,
                tempresult = '',
                D = 0);
            }
            return result + tempresult;
        }
        

            public static function des_createKeys(e) {
                var t = 'charCodeAt',
                pc2bytes0 = new Array(0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964),
                pc2bytes1 = new Array(0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697),
                pc2bytes2 = new Array(0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272),
                pc2bytes3 = new Array(0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144),
                pc2bytes4 = new Array(0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256),
                pc2bytes5 = new Array(0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488),
                pc2bytes6 = new Array(0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746),
                pc2bytes7 = new Array(0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568),
                pc2bytes8 = new Array(0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578),
                pc2bytes9 = new Array(0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488),
                pc2bytes10 = new Array(0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800),
                pc2bytes11 = new Array(0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744),
                pc2bytes12 = new Array(0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128),
                pc2bytes13 = new Array(0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261);
                var n = e.length >= 24 ? 3 : 1, r = new Array(32 * n), s = new Array(0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0), o, u, a = 0, f = 0, l,left,right;

                for (var c = 0; c < n; c++) {
                    left = e[t](a++) << 24 | e[t](a++) << 16 | e[t](a++) << 8 | e[t](a++),
                    right = e[t](a++) << 24 | e[t](a++) << 16 | e[t](a++) << 8 | e[t](a++),
                    l = (left >>> 4 ^ right) & 252645135,
                    right ^= l,
                    left ^= l << 4,
                    l = (right >>> -16 ^ left) & 65535,
                    left ^= l,
                    right ^= l << -16,
                    l = (left >>> 2 ^ right) & 858993459,
                    right ^= l,
                    left ^= l << 2,
                    l = (right >>> -16 ^ left) & 65535,
                    left ^= l,
                    right ^= l << -16,
                    l = (left >>> 1 ^ right) & 1431655765,
                    right ^= l,
                    left ^= l << 1,
                    l = (right >>> 8 ^ left) & 16711935,
                    left ^= l,
                    right ^= l << 8,
                    l = (left >>> 1 ^ right) & 1431655765,
                    right ^= l,
                    left ^= l << 1,
                    l = left << 8 | right >>> 20 & 240,
                    left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240,
                    right = l;

                    for (var i = 0; i < s.length; i++)
                        s[i] ? (left = left << 2 | left >>> 26,
                        right = right << 2 | right >>> 26) : (left = left << 1 | left >>> 27,
                        right = right << 1 | right >>> 27),
                        left &= -15,
                        right &= -15,
                        o = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15],
                        u = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15],
                        l = (u >>> 16 ^ o) & 65535,
                        r[f++] = o ^ l,
                        r[f++] = u ^ l << 16;
                }
                return r;

            }
            

            public static function stringToHex(e) {
                var t = 'charCodeAt'
                  , n = ''
                  , r = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
                for (var i = 0; i < e.length; i++)
                    n += r[e[t](i) >> 4] + r[e[t](i) & 15];
                return n
            }


        }

        }";


    }

代碼邏輯簡要說明:

1.GetValidateCode方法:通過GET請求獲取登錄驗證碼,並顯示在winform的界面上,以便用戶可以參照輸入,當然如果能夠使用第三方打碼工具自動識別驗證碼那就更簡單了。

2.HttpPost方法:構建POST請求登錄,並返回HttpWebResponse對象

3.從頭部取得跳轉的位置string newUrl = rs.Headers["Location"].ToString();如果是Default頁面且包含message,則通過正則取到message信息併在winform界面上顯示報錯。

4.jScriptClass這個是從中國人才熱線網站COPY的加密演算法邏輯,JScriptRun就是執行JS加密演算法並得到結果。

5.BaseUtil.OpenAdminPage方法:設置IE COOKIE,並用IE打開管理後臺網址;

登錄人才熱線網站的關鍵點在於:JS加密及驗證碼

用法如下:

                    var httpLoginCjol = new HttpLoginCjolHelper();
                    string result = httpLoginCjol.Login(txtCjolUid.Text.Trim(), txtCjolPwd.Text);
                    if (!string.IsNullOrEmpty(result))
                    {
                        MessageBox.Show("登錄中國人才熱線網站失敗,原因:" + result, "登錄失敗提示");
                    }

  

登錄前程無憂:HttpLogin51JobHelper

    public class HttpLogin51JobHelper
    {
        private CookieContainer web51jobCookies = new CookieContainer();

        public string Login(string uName, string uId, string pwd)
        {
            string langType, accessKey, fksc, hidEhireGuid, hidRetUrl;
            ReadHomePageData(out langType, out accessKey, out fksc, out hidEhireGuid, out hidRetUrl);
            string loginUrl = "https://ehirelogin.51job.com/Member/UserLogin.aspx";
            var rs = HttpPost(loginUrl, new Dictionary<string, string>
            {
                {"ctmName",uName},{"userName",uId},
                {"password",pwd},{"checkCode",""},
                {"oldAccessKey",accessKey},{"langtype",langType},
                {"isRememberMe","false"},{"sc",fksc},
                {"ec",hidEhireGuid},{"returl",hidRetUrl},
                {"referrurl","http://ehire.51job.com/"}
            });

            string newUrl = rs.Headers["Location"].ToString(); // "http://ehire.51job.com/Candidate/SearchResumeIndexNew.aspx";
            if (newUrl.IndexOf("errorId=", StringComparison.OrdinalIgnoreCase) > 0)
            {
                return GetLoginErrMsg(newUrl);
            }

            //string rsString = GetResponseContent(rs);

            BaseUtil.OpenAdminPage(web51jobCookies, new Uri(newUrl));

            return null;
        }

        private void ReadHomePageData(out string langType, out string accessKey, out string fksc, out string hidEhireGuid, out string hidRetUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ehire.51job.com/");
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
            request.CookieContainer = web51jobCookies;
            request.Host = "ehire.51job.com";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string rspContent = GetResponseContent(response);

            langType = "Lang=&Flag=1"; //getHiddenValueByElementId("hidLangType", rspContent);
            accessKey = getHiddenValueByElementId("hidAccessKey", rspContent);
            fksc = getHiddenValueByElementId("fksc", rspContent);
            hidEhireGuid = getHiddenValueByElementId("hidEhireGuid", rspContent);
            hidRetUrl = getHiddenValueByElementId("hidRetUrl", rspContent);
        }

        private string GetLoginErrMsg(string errUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(errUrl);
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
            request.CookieContainer = web51jobCookies;
            request.Host = "ehire.51job.com";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string rspContent = GetResponseContent(response);

            string pattren = @"<div\s+id='errOther'.+<a>(?<msg>.+)</a></div>";
            var regx = new System.Text.RegularExpressions.Regex(pattren, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string errMsg = regx.Match(rspContent).Groups["msg"].Value;
            return errMsg;
        }

        private HttpWebResponse HttpPost(string url, Dictionary<string, string> postData)
        {

            string postDataContent = null;
            foreach (var kv in postData)
            {
                postDataContent += string.Format("&{0}={1}", kv.Key, kv.Value);
            }
            postDataContent = postDataContent.Substring(1);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] data = Encoding.UTF8.GetBytes(postDataContent);
            request.ContentLength = data.Length;
            request.AllowAutoRedirect = false;
            request.CookieContainer = web51jobCookies;
            request.Host = "ehire.51job.com";
            request.Headers.Set("Origin", "http://ehire.51job.com");
            request.Referer = "http://ehire.51job.com";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36";
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(data, 0, data.Length);
            myRequestStream.Close();
            myRequestStream = null;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            return response;
        }

        private string getHiddenValueByElementId(string eId, string body)
        {
            string pattren = "id=\"" + eId + "\"\\s+value=\"(?<evalue>\\w+)\"";
            var regx = new System.Text.RegularExpressions.Regex(pattren, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (regx.IsMatch(body))
            {
                return regx.Match(body).Groups["evalue"].Value;
            }

            return string.Empty;
        }

        private string GetResponseContent(HttpWebResponse response)
        {
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
    }

代碼邏輯簡要說明:

1.ReadHomePageData方法:請求登錄頁面,獲取隱藏域的欄位信息

2.HttpPost方法:構建POST請求登錄,並返回HttpWebResponse對象

3.從頭部取得跳轉的位置string newUrl = rs.Headers["Location"].ToString();如果包含errorId,則通過請求該error頁面獲取錯誤信息GetLoginErrMsg併在winform界面上顯示報錯。

4.BaseUtil.OpenAdminPage方法:設置IE COOKIE,並用IE打開管理後臺網址;

登錄前程無憂網站的關鍵點在於:取得登錄頁面的隱藏域的欄位信息

用法如下:

                    var httpLogin51Job = new HttpLogin51JobHelper();
                    string result = httpLogin51Job.Login(txt51JobUName.Text.Trim(), txt51JobUid.Text.Trim(), txt51JobPwd.Text);
                    if (!string.IsNullOrEmpty(result))
                    {
                        MessageBox.Show("登錄前程無憂網站失敗,原因:" + result, "登錄失敗提示");
                    }

 

以下是如何設置IE COOKIE及通過IE打開指定網站的方法:

        public static void OpenAdminPage(CookieContainer cookies, Uri rsUri)
        {

            foreach (Cookie cookie in cookies.GetCookies(rsUri)) //將cookie設置為瀏覽的cookie  
            {
                InternetSetCookie(
                     "http://" + cookie.Domain.ToString(),
                     cookie.Name.ToString(),
                     cookie.Value.ToString() + ";expires=" + DateTime.UtcNow.AddDays(1).ToString("R"));
            }

            System.Diagnostics.Process.Start("iexplore.exe", rsUri.AbsoluteUri); //打開瀏覽器  

        }

  

關於C#執行Javascript方法有如下幾種:(我這裡僅做一個彙總,可能不止這麼多)

第一種:引用:Microsoft.JScript.DLL,然後使用:JScriptCodeProvider對象來動態編譯jscript腳本(CompileAssemblyFromSource)生成程式集,最後通過這個JS程式集反射執行JS方法;參考說明:http://www.cnblogs.com/xdpxyxy/archive/2013/06/12/3132868.html

第二種:引用:Interop.MSScriptControl.dll,然後使用Eval執行腳本內容,參考說明:http://www.cnblogs.com/preacher/p/6347251.html   、  http://www.cnblogs.com/feiyuhuo/p/5474790.html

第三種:引用:開源項目 Javascript .NET(Noesis.Javascript.dll、msvcp100.dll、msvcr100.dll複製到bin目錄下),然後使用JavascriptContext的Run方法執行,參考說明:http://www.cnblogs.com/yjmyzz/p/3359204.html

第四種:引用:Microsoft.JScript.Vsa(Microsoft.JScript、Microsoft.Vsa),然後使用Microsoft.JScript.Eval.JScriptEvaluate方法執行,參考說明:http://www.cnblogs.com/yjmyzz/p/3359204.html

第五種:在winform窗體中加入 WebBrowser 控制項,然後將JS通過Url或直接設置DocumentText,最後利用webBrowser1.Document.InvokeScript方法執行WebBrowser 控制項包含的JS方法,參考說明:http://blog.csdn.net/luxiaoyu_sdc/article/details/6896451 、 http://www.cnblogs.com/feiyuhuo/p/5474790.html (僅winform項目適用)

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天學習angularjs向資料庫添加數據。學習此篇,得從以往幾篇開始,因為那還有創建數據表等演示。現在來創建一個添加的存儲過程: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[usp_Goods_I ...
  • c 介面使用詳解 c 中介面隱式與顯示實現 c 中介面可以隱式實現、顯示實現,隱式實現更常使用、顯示實現較少使用 其區別在於 1. 顯示實現避免介面函數簽名衝突 2. 顯示實現只可以以介面形式調用 3. 顯示實現其子類需無法繼承介面 4. 隱式實現可以撕裂調用、可以介面調用 5. 隱式實現其子類可以 ...
  • 下載並引入兩個dll文件 NPinyin.dll 和 ChnCharInfo.dll 其實這兩個dll 任何一個都可以實現漢字轉拼音,然而 NPinyin.dll 收錄的漢字並不全,但是很人性化,能識別一些常用的漢字。ChnCharInfo.dll 是微軟的很全但是不人性化。另外本套代碼外有一個自己 ...
  • DotBPE.RPC是一款基於dotnet core編寫的RPC框架,而它的爸爸DotBPE,目標是實現一個開箱即用的微服務框架,但是它還差點意思,還僅僅在構思和嘗試的階段。但不管怎麼說RPC是微服務的基礎,先來講講RPC的實現吧。DotBPE.RPC底層通信預設實現基於[DotNetty](htt... ...
  • 工廠方法模式(Factory Method) 工廠方法屬於創建型模式中的一種,用於在不指定待創建對象的具體類的情況下創建對象,隱藏了對象創建的複雜性。客戶面向介面或抽象類進行編碼,而Factory類負責具體類的創建。通常,Factory類有一個返回介面或抽象類的靜態方法,客戶提供某種信息,然後由根據 ...
  • 主要介紹ASP.NETMVC 應用提速的六種方法,因為沒有人喜歡等待,所以介紹幾種常用的優化方法。 大家可能會遇到排隊等待,遇到紅燈要等待,開個網頁要等待,等等等。 理所當然,沒有人喜歡等待網頁慢吞吞地載入,尤其是在移動端訪問網站時。其實,Web 開發者敏感的神經決定了我們等待與否。 現在,快速響應 ...
  • ...
  • 本文原創,轉載請註明出處:http://www.cnblogs.com/AdvancePikachu/p/6856374.html 首先,總結了下最近工作中關於攝像機漫游的功能, 腳本如下: 1 Transform _Camera; 2 public LayerMask mask; 3 4 publ ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...