之前為了便於人事部門招聘登錄網站更簡潔高效,免去每天頻繁輸網址、用戶名、密碼等相關登錄信息,特基於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項目適用)