1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Net; 5 using System.IO; 6 using System.Collections.Generic; 7 8 namespace Common 9 { 10 public class HttpHelper 11 { 12 #region 淘寶系列 13 public static string GetHtmlHttp(string URL, string postData, string cookie, out string header) 14 { 15 return GetHtmlHttp("https://cas.sdo.com:80", URL, postData, cookie, out header); 16 } 17 public static string GetHtmlHttp(string server, string URL, string postData, string cookie, out string header) 18 { 19 byte[] byteRequest = Encoding.Default.GetBytes(postData); 20 return GetHtmlHttp(server, URL, byteRequest, cookie, out header); 21 } 22 public static string GetHtmlHttp(string server, string URL, byte[] byteRequest, string cookie, out string header) 23 { 24 byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header); 25 Stream getStream = new MemoryStream(bytes); 26 StreamReader streamReader = new StreamReader(getStream, Encoding.Default); 27 string getString = streamReader.ReadToEnd(); 28 streamReader.Close(); 29 getStream.Close(); 30 return getString; 31 } 32 public static string GetHtmlHttp(string URL, string cookie, ref string header) 33 { 34 Uri baseuri = new Uri(URL); 35 string server = "http://" + baseuri.Host; 36 return GetHtmlHttp(URL, cookie, ref header, server); 37 } 38 public static string GetHtmlHttp(string URL, string cookie, ref string header, string server) 39 { 40 HttpWebRequest httpWebRequest; 41 HttpWebResponse webResponse; 42 Stream getStream; 43 StreamReader streamReader; 44 string getString = ""; 45 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL); 46 httpWebRequest.Accept = "*/*"; 47 httpWebRequest.Referer = "http://www.taobao.com/"; 48 CookieContainer co = new CookieContainer(); 49 //cookie = HeaderCheck(header, cookie); 50 co.SetCookies(new Uri(server), cookie); 51 httpWebRequest.CookieContainer = co; 52 httpWebRequest.UserAgent = 53 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"; 54 httpWebRequest.Method = "GET"; 55 webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 56 header = webResponse.Headers.ToString(); 57 getStream = webResponse.GetResponseStream(); 58 streamReader = new StreamReader(getStream, Encoding.Default); 59 getString = streamReader.ReadToEnd(); 60 61 streamReader.Close(); 62 getStream.Close(); 63 return getString; 64 } 65 public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header) 66 { 67 long contentLength; 68 HttpWebRequest httpWebRequest; 69 HttpWebResponse webResponse; 70 Stream getStream; 71 72 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL); 73 CookieContainer co = new CookieContainer(); 74 co.SetCookies(new Uri(server), cookie); 75 76 httpWebRequest.CookieContainer = co; 77 78 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 79 httpWebRequest.Accept = 80 "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; 81 httpWebRequest.Referer = "http://zh.sdo.com"; 82 httpWebRequest.UserAgent = 83 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)"; 84 httpWebRequest.Method = "Post"; 85 httpWebRequest.ContentLength = byteRequest.Length; 86 Stream stream; 87 stream = httpWebRequest.GetRequestStream(); 88 stream.Write(byteRequest, 0, byteRequest.Length); 89 stream.Close(); 90 webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 91 header = webResponse.Headers.ToString(); 92 getStream = webResponse.GetResponseStream(); 93 contentLength = webResponse.ContentLength; 94 95 byte[] outBytes = new byte[contentLength]; 96 outBytes = ReadFully(getStream); 97 getStream.Close(); 98 return outBytes; 99 } 100 public static byte[] ReadFully(Stream stream) 101 { 102 byte[] buffer = new byte[128]; 103 using (MemoryStream ms = new MemoryStream()) 104 { 105 while (true) 106 { 107 int read = stream.Read(buffer, 0, buffer.Length); 108 if (read <= 0) 109 return ms.ToArray(); 110 ms.Write(buffer, 0, read); 111 } 112 } 113 } 114 /// <summary> 115 /// post數據處理 116 /// </summary> 117 /// <returns></returns> 118 public Byte[] StringToByte() 119 { 120 //StringBuilder buf = new StringBuilder(); 121 //int i = 0; 122 //foreach (String key in _PostData.Keys) 123 //{ 124 // if (i > 0) buf.Append("&"); 125 // buf.Append(key + "=" + _PostData[key]); 126 // i++; 127 //} 128 //if (i == 0) 129 // return new byte[0]; 130 //else 131 // return Encoding.GetEncoding(PostDataCharset).GetBytes(buf.ToString()); 132 return null; 133 } 134 135 /// <summary> 136 /// 淘寶登錄專用 137 /// </summary> 138 /// <param name="url"></param> 139 /// <param name="methed"></param> 140 /// <param name="param"></param> 141 /// <param name="referer"></param> 142 /// <param name="html"></param> 143 /// <param name="header"></param> 144 /// <param name="cookie"></param> 145 /// <returns></returns> 146 public static bool GetHtmlFindHeaders(string url, string methed, string param, string referer, out string html, out string header, string cookie) 147 { 148 try 149 { 150 HttpWebRequest httpWebRequest; 151 HttpWebResponse webResponse; 152 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 153 httpWebRequest.KeepAlive = true; 154 httpWebRequest.AllowAutoRedirect = true; 155 httpWebRequest.MaximumAutomaticRedirections = 10; 156 httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.01; Windows NT 5.0"; 157 httpWebRequest.Timeout = 10000; 158 httpWebRequest.Accept = "*/*"; 159 httpWebRequest.Referer = "https://www.taobao.com/"; 160 CookieContainer co = new CookieContainer(); 161 string server = "http://" + (new Uri(url)).Host; 162 if (cookie.Length > 0) 163 { 164 co.SetCookies(new Uri(server), cookie); 165 httpWebRequest.CookieContainer = co; 166 } 167 //httpWebRequest.UserAgent = 168 // "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"; 169 httpWebRequest.Method = methed; 170 171 172 if (methed.ToLower() == "post") 173 { 174 //POST 提交 175 byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(param); 176 if (httpWebRequest.ContentType == null) 177 httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 178 httpWebRequest.ContentLength = postData.Length; 179 Stream reqStream = httpWebRequest.GetRequestStream(); 180 reqStream.Write(postData, 0, postData.Length); 181 reqStream.Close(); 182 183 } 184 185 webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 186 StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.Default); 187 html = sr.ReadToEnd(); 188 header = webResponse.Headers.ToString(); 189 return true; 190 } 191 catch (Exception ex) 192 { 193 html = "出現異常(HttpHelper.GetHtmlFindHeaders):" + ex.Message; 194 header = null; 195 return false; 196 197 } 198 } 199 #endregion 200 201 202 public static bool GetHtmlOA(string url, string methed, string param, out string html, out string header, string cookies) 203 { 204 try 205 { 206 var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 207 httpWebRequest.KeepAlive = true; 208 httpWebRequest.AllowAutoRedirect = true; 209 httpWebRequest.MaximumAutomaticRedirections = 10; 210 httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.01; Windows NT 5.0"; 211 httpWebRequest.Timeout = 10000; 212 httpWebRequest.Accept = "*/*"; 213 httpWebRequest.Method = methed; 214 var co = new CookieContainer(); 215 string server = "http://" + (new Uri(url)).Host; 216 if (cookies.Length > 0) 217 { 218 co.SetCookies(new Uri(server), cookies); 219 httpWebRequest.CookieContainer = co; 220 } 221 222 if (methed.ToLower() == "post") 223 { 224 //POST 提交 225 byte[] postData = Encoding.UTF8.GetBytes(param); 226 if (httpWebRequest.ContentType == null) 227 httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 228 httpWebRequest.ContentLength = postData.Length; 229 Stream reqStream = httpWebRequest.GetRequestStream(); 230 reqStream.Write(postData, 0, postData.Length); 231 reqStream.Close(); 232 233 } 234 235 HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 236 StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); 237 html = sr.ReadToEnd(); 238 header = webResponse.Headers.ToString(); 239 return true; 240 } 241 catch (Exception ex) 242 { 243 html = "出現異常(HttpHelper.GetHtmlFindHeaders):" + ex.Message; 244 header = null; 245 return false; 246 247 } 248 } 249 250 /// <summary> 251 /// 獲取html 252 /// </summary> 253 /// <param name="url"></param> 254 /// <param name="methed"></param> 255 /// <param name="param"></param> 256 /// <param name="referer"></param> 257 /// <param name="html"></param> 258 /// <returns></returns> 259 public static bool GetHtml(string url, string methed, string param, string referer, out string html, out string header) 260 { 261 return GetHtml(url, methed, param, referer, "gbk", out html, out header); 262 } 263 264 /// <summary> 265 /// 獲取html 266 /// </summary> 267 /// <param name="url"></param> 268 /// <param name="methed"></param> 269 /// <param name="param"></param> 270 /// <param name="referer"></param> 271 /// <param name="encode"></param> 272 /// <param name="html"></param> 273 /// <param name="header">返回一個頭部</param> 274 /// <returns></returns> 275 public static bool GetHtml(string url, string methed, string param, string referer, string encode, out string html, out string header) 276 { 277 if (param != null && methed == "get" && param.Length > 0) 278 { 279 if (url.IndexOf("?") >= 0) 280 { 281 url += "&" + param; 282 } 283 else 284 { 285 url += "?" + param; 286 } 287 } 288 289 try 290 { 291 //WebRequest r; 292 MSXML2.XMLHTTPClass mx = new MSXML2.XMLHTTPClass(); 293 mx.open(methed, url, false, null, null); 294 mx.setRequestHeader("Content-Length", param.Length.ToString()); 295 mx.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 296 mx.send(param); 297 298 /* 299 0:請求未初始化(還沒有調用 open())。 300 1:請求已經建立,但是還沒有發送(還沒有調用 send())。 301 2:請求已發送,正在處理中(通常現在可以從響應中獲取內容頭)。 302 3:請求在處理中;通常響應中已有部分數據可用了,但是服務器還沒有完成響應的生成。 303 4:響應已完成;您可以獲取並使用服務器的響應了。 304 */ 305 if (mx.readyState != 4) 306 { 307 html = ""; 308 header = null; 309 return false; 310 } 311 html = mx.responseText; 312 header = mx.getAllResponseHeaders(); 313 return true; 314 } 315 catch (Exception ex) 316 { 317 html = "出現異常(HttpHelper.GetHTML):" + ex.Message; 318 //System.Windows.Forms.MessageBox.Show(html); 319 header = null; 320 return false; 321 } 322 } 323 324 public static bool GetBmp(string url, string methed, string param, out System.Drawing.Bitmap bmp) 325 { 326 if (param != null && methed == "get" && param.Length > 0) 327 { 328 if (url.IndexOf("?") >= 0) 329 { 330 url += "&" + param; 331 } 332 else 333 { 334 url += "?" + param; 335 } 336 } 337 338 try 339 { 340 MSXML2.XMLHTTPClass mx = new MSXML2.XMLHTTPClass(); 341 mx.open(methed, url, false, null, null); 342 mx.setRequestHeader("Content-Length", param.Length.ToString()); 343 mx.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 344 mx.send(param); 345 346 if (mx.readyState != 4) 347 { 348 bmp = null; 349 return false; 350 } 351 352 object o = mx.responseBody; 353 354 byte[] buff = (byte[])o; 355 MemoryStream stream = new MemoryStream(buff); 356 357 if (stream == null) 358 { 359 bmp = null; 360 return false; 361 } 362 363 bmp = new System.Drawing.Bitmap(stream); 364 365 return true; 366 } 367 catch (Exception ex) 368 { 369 //日志記錄 370 bmp = null; 371 return false; 372 } 373 } 374 375 376 #region 公用 377 378 /// <summary> 379 /// 通過頭部信息截取出所Set-Cookie 並鏈接為一個字符串 380 /// </summary> 381 /// <param name="str"></param> 382 /// <returns></returns> 383 public static string ToCookies(string str) 384 { 385 string[] arr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 386 StringBuilder buf = new StringBuilder(); 387 foreach (var item in arr) 388 { 389 if (item.StartsWith("Set-Cookie: ")) 390 { 391 buf.Append(GetCookieToString(item.Substring(12))); 392 //int intStart = item.IndexOf(";", System.StringComparison.Ordinal); 393 //string strCookie = item.Substring(12, intStart - 11); 394 //buf.Append(strCookie); 395 } 396 } 397 return buf.ToString(); 398 } 399 400 401 /// <summary> 402 /// 通過頭部信息截取出所Set-Cookie 找到 名稱為key的 cookie 403 /// </summary> 404 /// <param name="str"></param> 405 /// <param name="key">要在header中提取的cookie名</param> 406 /// <returns></returns> 407 public static string ToCookies(string str, string key) 408 { 409 try 410 { 411 string[] arr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 412 413 var cookieStr = ""; 414 foreach (var item in arr) 415 { 416 if (item.StartsWith("Set-Cookie: ")) 417 { 418 //此cookie字符串 是用,鏈接的 419 cookieStr = GetCookieToString(item.Substring(12)); 420 } 421 } 422 if (cookieStr.Length > 0) 423 { 424 var strs = cookieStr.Split(','); 425 foreach (var item in strs) 426 { 427 if (item.StartsWith(key)) 428 { 429 return item; 430 } 431 } 432 } 433 return ""; 434 } 435 catch 436 { 437 return ""; 438 } 439 } 440 441 /// <summary> 442 /// 修改字符串 443 /// </summary> 444 /// <param name="str"></param> 445 /// <returns></returns> 446 public static string GetCookieToString(string str) 447 { 448 string[] arr = str.Split(','); 449 StringBuilder buf = new StringBuilder(); 450 foreach (var item in arr) 451 { 452 string cookieStr = ""; 453 int strCount = item.IndexOf(";", System.StringComparison.Ordinal); 454 if (strCount > 0) 455 { 456 cookieStr = item.Substring(0, strCount); 457 } 458 else 459 { 460 cookieStr = item; 461 } 462 if (cookieStr.IndexOf("GMT", System.StringComparison.Ordinal) <= 0) 463 { 464 Console.WriteLine(cookieStr); 465 buf.Append(cookieStr); 466 buf.Append(","); 467 } 468 if (cookieStr.IndexOf('&') > 0) 469 { 470 Console.WriteLine("-----------" + cookieStr); 471 } 472 } 473 return buf.ToString().TrimEnd(','); 474 } 475 476 /// <summary> 477 /// 驗證cookies的個數 478 /// </summary> 479 /// <param name="str"></param> 480 /// <returns></returns> 481 public static string CheckCookieNum(string str) 482 { 483 //var need = new[] { "uc1", "uc3", "existShop", "lgc", "tracknick", "cookie2", "cookie1", "_cc_", "_l_g_", "_nk_", "cookie17", "_tb_token_","t" , |---"tbcp", "skt", "lc"}; 484 var need = new[] { "uc1", "uc3", "existShop", "lgc", "tracknick", "v", "sg", "cookie2", "mt", "cookie1", "unb", "t", "_cc_", "tg", "_l_g_", "_nk_", "cookie17", "_tb_token_" }; 485 var strs = str.Split(','); 486 var sub = new StringBuilder(); 487 //if (strs.Length > 19) 488 if (true) 489 { 490 foreach (var item in need) 491 { 492 foreach (var val in strs) 493 { 494 if (val.StartsWith(item + "=")) 495 { 496 sub.Append(val + ","); 497 } 498 } 499 } 500 return sub.ToString().TrimEnd(','); 501 } 502 return str; 503 } 504 505 /// <summary> 506 /// 替換某一個cookies 507 /// </summary> 508 /// <param name="oldStr">舊cookies</param> 509 /// <param name="newHeader">新header</param> 510 /// <param name="key">要替換的key</param> 511 /// <returns>替換好的header</returns> 512 public static string ReaplceCookie(string oldStr, string newHeader, string key) 513 { 514 var oldStrs = oldStr.Split(','); 515 var newStrs = ToCookies(newHeader).Split(','); 516 var sub = new StringBuilder(); 517 foreach (var item in oldStrs) 518 { 519 if (item.StartsWith(key)) 520 { 521 var isRe = false; 522 foreach (var val in newStrs) 523 { 524 if (val.StartsWith(key)) 525 { 526 sub.Append(val + ","); 527 isRe = true; 528 } 529 } 530 if (!isRe) 531 { 532 sub.Append(item + ","); 533 } 534 } 535 else 536 { 537 sub.Append(item + ","); 538 } 539 } 540 return sub.ToString().TrimEnd(','); 541 } 542 543 544 /// <summary> 545 /// 結合heders和cookies 546 /// </summary> 547 /// <param name="headers"></param> 548 /// <param name="cookies"></param> 549 /// <returns></returns> 550 public static string HeaderCheck(string headers, string cookies) 551 { 552 var str = ToCookies(headers); 553 if (str.Length == 0) 554 { 555 return cookies; 556 } 557 else 558 { 559 var buf = new StringBuilder(); 560 buf.Append(GetCookieToString(str)); 561 if (cookies.Length > 0) 562 { 563 buf.Append(","); 564 } 565 buf.Append(cookies); 566 return buf.ToString(); 567 } 568 } 569 #endregion 570 571 } 572 }
此類是自定義的http幫助類,關鍵的點就在其中。
下面的類是http的請求,有post和get

1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.IO; 8 using Newtonsoft.Json; 9 using Newtonsoft.Json.Linq; 10 11 namespace Common 12 { 13 public class LoginHelper 14 { 15 16 private string Username; 17 private string Password; 18 private string Code; 19 private string Cookie; 20 private bool NeedCode; 21 22 public LoginHelper() 23 { 24 } 25 26 public LoginHelper(string username, string password, string code, string cookie, bool needcode) 27 { 28 Username = username; 29 Password = password; 30 Code = code; 31 Cookie = cookie; 32 NeedCode = needcode; 33 } 34 35 #region 登錄 36 37 /// <summary> 38 /// 登錄,返回1,登錄成功 39 /// </summary> 40 /// <returns></returns> 41 public bool Login(out string returnMsg, out string headers) 42 { 43 string loginMsg; 44 try 45 { 46 loginMsg = LoginRun(out headers); 47 } 48 catch (Exception ex) 49 { 50 returnMsg = "出現異常(PostProHandler.Login):請確認能否手動登錄淘寶助手。" + ex.Message; 51 headers = null; 52 return false; 53 } 54 55 if (loginMsg != "1") 56 { 57 returnMsg = loginMsg; 58 } 59 else 60 { 61 returnMsg = "登錄成功"; 62 return true; 63 64 } 65 return false; 66 } 67 68 /// <summary> 69 /// 返回1,登錄成功 70 /// </summary> 71 /// <returns></returns> 72 public string LoginRun(out string headers) 73 { 74 75 Console.WriteLine("開始模擬登錄"); 76 const string loginUrl = "https://login.taobao.com/member/login.jhtml"; //v1.2 77 List<string> paramList = new List<string>(); 78 #region 暫不用字段 79 //paramList.Add("CtrlVersion=1,0,0,7"); 80 //paramList.Add("fc=default"); 81 //paramList.Add("from=tb"); 82 //paramList.Add("loginsite=0"); 83 //paramList.Add("newlogin=1"); 84 //paramList.Add("style=default"); 85 //paramList.Add("support=000001"); 86 #endregion 87 paramList.Add("sub=false"); 88 paramList.Add("callback=1"); 89 paramList.Add("loginType=3"); 90 paramList.Add("TPL_redirect_url=" + "http://www.taobao.com/"); 91 paramList.Add("TPL_username=" + Username); 92 paramList.Add("TPL_password=" + UrlEncode(Password)); 93 if (NeedCode) 94 { 95 //驗證碼 96 paramList.Add("need_check_code=yes"); 97 paramList.Add("TPL_checkcode=" + Code); 98 } 99 //執行登錄 100 string param = string.Join("&", paramList.ToArray()); //v1.3 101 string html; 102 if (!NeedCode) 103 { 104 Cookie = ""; 105 } 106 //登錄后的權威headers 107 if (!HttpHelper.GetHtmlFindHeaders(loginUrl, "post", param, "", out html, out headers, Cookie)) 108 { 109 return "登錄失敗(PostProHandler.LoginRun):"; 110 } 111 #region 解析登錄狀態 112 JObject jsonObj = (JObject)JsonConvert.DeserializeObject(html); 113 bool state = (bool)jsonObj["state"]; 114 string message = jsonObj["message"].ToString(); 115 116 117 ////登錄成功 118 if (state)//v1.2 119 { 120 return "1"; 121 } 122 if (message.Length > 0) 123 { 124 return message; 125 } 126 127 if (html.IndexOf("您輸入的驗證碼不正確", StringComparison.Ordinal) >= 0 || html.IndexOf("驗證碼錯誤", StringComparison.Ordinal) >= 0) 128 { 129 return "驗證碼輸入錯誤"; 130 } 131 132 if (html.IndexOf("您輸入的密碼和登錄名不匹配", StringComparison.Ordinal) >= 0) 133 { 134 return "用戶名或密碼錯誤"; 135 } 136 137 if (html.IndexOf("暫時無法登錄", StringComparison.Ordinal) >= 0) 138 { 139 return "暫時無法登錄_凍結"; 140 } 141 #endregion 142 return "未知登錄錯誤"; 143 } 144 145 #endregion 146 147 #region 驗證碼相關 148 149 public static bool CheckIfNeedCode(string userName, out string html) 150 { 151 var url = "https://login.taobao.com/member/request_nick_check.do?_input_charset=UTF-8&username=" + userName; 152 string headers; 153 if (!HttpHelper.GetHtmlFindHeaders(url, "get", "", "", out html, out headers, "")) 154 { 155 } 156 JObject jsonObj = (JObject)JsonConvert.DeserializeObject(html); 157 bool needCode = jsonObj["needcode"].ToString().ToLower().Equals("true"); 158 return needCode; 159 } 160 161 #endregion 162 163 #region 身份牌獲取 164 165 public static bool GetCardTokenCookie(ref string cookie, string param) 166 { 167 string loginUrl = "https://login.taobao.com/member/vst.htm?callback=jsonp116&" + param; //v1.2 168 string html = ""; 169 string header = ""; 170 if (!HttpHelper.GetHtmlFindHeaders(loginUrl, "get", "", "", out html, out header, cookie)) 171 { 172 } 173 174 //if (HttpHelper.GetHtml(loginUrl, "get", "", "", out html, out header)) 175 //{ 176 //} 177 return true; 178 } 179 180 #endregion 181 182 #region 獲取驗證碼圖片 183 184 /// <summary> 185 /// 獲取驗證碼圖片 186 /// </summary> 187 /// <returns></returns> 188 public static Image GetCodeImg(out string cookie) 189 { 190 Console.WriteLine("打開阿里登錄頁,cookie2載入"); 191 string html; 192 const string url = "https://login.taobao.com/member/login.jhtml?from=tb&full_redirect=true"; 193 string headers = ""; 194 HttpHelper.GetHtml(url, "get", "", "", out html, out headers); 195 Console.WriteLine("結束打開阿里登錄頁,cookie2載入"); 196 197 Console.WriteLine("獲取cookie2"); 198 cookie = FullWebBrowserCookie.GetCookieInternal(new Uri(url), true); 199 string cookie2 = FullWebBrowserCookie.GetCookieValue("cookie2", new Uri(url), true); 200 Console.WriteLine("結束獲取cookie2"); 201 202 string codePath = "https://regcheckcode.taobao.com/auction/checkcode?sessionID=" + cookie2; 203 204 Bitmap bmp; 205 GetBmp(codePath, "get", out bmp); 206 207 return bmp; 208 } 209 210 //獲取驗證碼圖片 211 private static void GetBmp(string url, string method, out Bitmap bmp) 212 { 213 var request = (HttpWebRequest)WebRequest.Create(url); 214 request.Timeout = 20000; 215 request.ServicePoint.ConnectionLimit = 100; 216 request.ReadWriteTimeout = 30000; 217 request.Method = method; 218 var response = (HttpWebResponse)request.GetResponse(); 219 if (response.StatusCode != HttpStatusCode.OK) 220 { 221 } 222 Stream resStream = response.GetResponseStream(); 223 bmp = null; 224 if (resStream != null) 225 { 226 bmp = new Bitmap(resStream); 227 } 228 229 //this.pictureBox1.Image = new Bitmap(resStream); 230 } 231 232 233 #endregion 234 235 #region 物品Post 236 /// <summary> 237 /// 物品post 238 /// </summary> 239 /// <param name="Ids"></param> 240 /// <param name="postName"></param> 241 /// <param name="postAction"></param> 242 /// <param name="postEvent"></param> 243 /// <param name="token"></param> 244 /// <param name="cookie"></param> 245 /// <param name="html"></param> 246 /// <returns></returns> 247 public static string PostGoods(string Ids, string postName, string postAction, string postEvent, string token, string cookie, out string html) 248 { 249 if (Ids.Length > 0) 250 { 251 const string loginUrl = "http://sell.taobao.com/auction/commodity/auction_list.htm?type=1"; //v1.2 252 List<string> paramList = new List<string>(); 253 paramList.Add(token); 254 paramList.Add("orderField=publishTime"); 255 paramList.Add("status=all"); 256 paramList.Add("orderType=desc"); 257 paramList.Add("oldPage=0"); 258 paramList.Add("type=1"); 259 paramList.Add("isFirstLogin=false"); 260 paramList.Add("shopCatName="); 261 paramList.Add("searchKeyword="); 262 paramList.Add("outID="); 263 paramList.Add("category="); 264 paramList.Add("scatid="); 265 paramList.Add("startNum="); 266 paramList.Add("endNum="); 267 paramList.Add("startPrice="); 268 paramList.Add("endPrice="); 269 paramList.Add(postEvent + "=1"); 270 paramList.Add("action=" + postAction); 271 paramList.Add("selectedItemIds=" + Ids); 272 paramList.Add("name=" + postName); 273 //paramList.Add("page=1"); 274 //執行登錄 275 string param = string.Join("&", paramList.ToArray()); //v1.3 276 //登錄后的權威headers 277 string headers; 278 if (!HttpHelper.GetHtmlFindHeaders(loginUrl + "&" + param, "get", param, "", out html, out headers, cookie)) 279 { 280 return "登錄失敗(PostProHandler.LoginRun):"; 281 } 282 else 283 { 284 return html; 285 } 286 } 287 html = null; 288 return null; 289 } 290 #endregion 291 292 #region 公用 293 294 /// <summary> 295 /// 將字符串URL編碼 296 /// </summary> 297 /// <param name="str"></param> 298 /// <returns></returns> 299 public static string UrlEncode(string str) 300 { 301 var sb = new StringBuilder(); 302 byte[] byStr = Encoding.UTF8.GetBytes(str); //默認是System.Text.Encoding.Default.GetBytes(str) 303 for (var i = 0; i < byStr.Length; i++) 304 { 305 sb.Append(@"%" + Convert.ToString(byStr[i], 16)); 306 } 307 308 return (sb.ToString()); 309 } 310 311 #endregion 312 } 313 314 }
下面是一個驗證碼的cookie獲取。貌似沒用到,也暫時記錄下來

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Net; 5 using System.Runtime.InteropServices; 6 using System.Security; 7 using System.Security.Permissions; 8 using System.Text; 9 using CookieHandler; 10 11 namespace CookieHandler 12 { 13 internal sealed class INativeMethods 14 { 15 #region enums 16 17 public enum ErrorFlags 18 { 19 ERROR_INSUFFICIENT_BUFFER = 122, 20 ERROR_INVALID_PARAMETER = 87, 21 ERROR_NO_MORE_ITEMS = 259 22 } 23 24 public enum InternetFlags 25 { 26 INTERNET_COOKIE_HTTPONLY = 8192, //Requires IE 8 or higher 27 INTERNET_COOKIE_THIRD_PARTY = 131072, 28 INTERNET_FLAG_RESTRICTED_ZONE = 16 29 } 30 31 #endregion 32 33 #region DLL Imports 34 35 [SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("wininet.dll", EntryPoint = "InternetGetCookieExW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] 36 internal static extern bool InternetGetCookieEx([In] string Url, [In] string cookieName, [Out] StringBuilder cookieData, [In, Out] ref uint pchCookieData, uint flags, IntPtr reserved); 37 38 #endregion 39 } 40 41 } 42 43 44 /// <SUMMARY></SUMMARY> 45 /// 取得WebBrowser的完整Cookie。 46 /// 因為默認的webBrowser1.Document.Cookie取不到HttpOnly的Cookie 47 /// IE7不兼容,IE8可以,其它未知 48 /// 49 public class FullWebBrowserCookie 50 { 51 public static Dictionary<string, string> GetCookieList(Uri uri, bool throwIfNoCookie) 52 { 53 Dictionary<string, string> dict = new Dictionary<string, string>(); 54 string cookie = GetCookieInternal(uri, throwIfNoCookie); 55 Console.WriteLine("FullWebBrowserCookie - 所有cookie:" + cookie); 56 string[] arrCookie = cookie.Split(';'); 57 foreach (var item in arrCookie) 58 { 59 string[] arr = item.Split('='); 60 string key = arr[0].Trim(); 61 string val = ""; 62 if (arr.Length >= 2) 63 { 64 val = arr[1].Trim(); 65 } 66 67 if (!dict.ContainsKey(key)) 68 { 69 dict.Add(key, val); 70 } 71 } 72 Console.WriteLine("FullWebBrowserCookie - cookie已載入dict,共" + dict.Count.ToString() + "項"); 73 74 return dict; 75 } 76 77 public static string GetCookieValue(string key, Uri uri, bool throwIfNoCookie) 78 { 79 Console.WriteLine("GetCookieValue"); 80 Dictionary<string, string> dict = GetCookieList(uri, throwIfNoCookie); 81 82 if (dict.ContainsKey(key)) 83 { 84 return dict[key]; 85 } 86 return ""; 87 } 88 89 [SecurityCritical] 90 public static string GetCookieInternal(Uri uri, bool throwIfNoCookie) 91 { 92 Console.WriteLine("GetCookieInternal"); 93 94 uint pchCookieData = 0; 95 string url = UriToString(uri); 96 uint flag = (uint)INativeMethods.InternetFlags.INTERNET_COOKIE_HTTPONLY; 97 98 //Gets the size of the string builder 99 if (INativeMethods.InternetGetCookieEx(url, null, null, ref pchCookieData, flag, IntPtr.Zero)) 100 { 101 pchCookieData++; 102 StringBuilder cookieData = new StringBuilder((int)pchCookieData); 103 104 //Read the cookie 105 if (INativeMethods.InternetGetCookieEx(url, null, cookieData, ref pchCookieData, flag, IntPtr.Zero)) 106 { 107 DemandWebPermission(uri); 108 return cookieData.ToString(); 109 } 110 } 111 112 int lastErrorCode = Marshal.GetLastWin32Error(); 113 114 if (throwIfNoCookie || (lastErrorCode != (int)INativeMethods.ErrorFlags.ERROR_NO_MORE_ITEMS)) 115 { 116 throw new Win32Exception(lastErrorCode); 117 } 118 119 return null; 120 } 121 122 private static void DemandWebPermission(Uri uri) 123 { 124 string uriString = UriToString(uri); 125 126 if (uri.IsFile) 127 { 128 string localPath = uri.LocalPath; 129 new FileIOPermission(FileIOPermissionAccess.Read, localPath).Demand(); 130 } 131 else 132 { 133 new WebPermission(NetworkAccess.Connect, uriString).Demand(); 134 } 135 } 136 private static string UriToString(Uri uri) 137 { 138 if (uri == null) 139 { 140 throw new ArgumentNullException("uri"); 141 } UriComponents components = (uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString); return new StringBuilder(uri.GetComponents(components, UriFormat.SafeUnescaped), 2083).ToString(); 142 } 143 }
下面這個類是請求之后獲得結果,然后去解析html,多為正則表達式

1 using System; 2 using System.Collections.Generic; 3 using System.Runtime.InteropServices; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 using Model; 7 using Newtonsoft.Json; 8 using Newtonsoft.Json.Linq; 9 10 namespace Common 11 { 12 public class RegexHelper 13 { 14 15 #region MyRegion 16 /// <summary> 17 /// 獲取html的selectedIds 18 /// </summary> 19 /// <returns></returns> 20 public static List<string> GetSelectedIds(string html, string strPattern) 21 { 22 ClearHtml(html); 23 List<string> list = RegexMatchHtmlMore(html, strPattern); 24 return list; 25 } 26 public static string GetStr(string html, string strPattern) 27 { 28 var str = RegexMatchHtml(html, strPattern); 29 return str; 30 } 31 32 #region 物品相關 33 34 /// <summary> 35 /// 獲取物品的數量 36 /// </summary> 37 /// <param name="html"></param> 38 /// <returns></returns> 39 public static int GetGoodsCount(string html) 40 { 41 ClearHtml(html); 42 string strPattern1 = string.Format("{0}\\s*(?<key>.*?),\\s*{1}", Regex.Escape("\"pagination\":"), Regex.Escape("\"items\":")); 43 var str = RegexMatchHtml(html, strPattern1); 44 var jsonObj = (JObject)JsonConvert.DeserializeObject(str); 45 //物品總數 46 var count = (int)jsonObj["totalRecord"]; 47 return count; 48 } 49 50 51 /// <summary> 52 /// 獲取當前所有產品 53 /// </summary> 54 /// <param name="html"></param> 55 /// <returns></returns> 56 public static List<Goods> GetGoods(string html) 57 { 58 ClearHtml(html); 59 string strPattern1 = string.Format("{0}\\s*(?<key>.*?),\\s*{1}", Regex.Escape("\"items\":"), Regex.Escape("\"alerts\":")); 60 var str = RegexMatchHtml(html, strPattern1); 61 var list = new List<Goods>(); 62 if (str.Length > 2) 63 { 64 list = GetGoodsByJosn(str); 65 } 66 return list; 67 } 68 69 /// <summary> 70 /// 通過json數據,分析返回 物品列表 71 /// </summary> 72 /// <param name="json"></param> 73 /// <returns></returns> 74 public static List<Goods> GetGoodsByJosn(string json) 75 { 76 var jsonObj = (JArray)JsonConvert.DeserializeObject(json); 77 var list = new List<Goods>(); 78 foreach (JToken item in jsonObj) 79 { 80 var model = new Goods 81 { 82 Id = item["id"].ToString(), 83 TitleContent = item["title"]["content"].ToString(), 84 LastModify = item["lastModify"].ToString(), 85 PublishTime = item["publishTime"].ToString(), 86 PriceValue = item["price"]["value"].ToString(), 87 Image = item["image"].ToString(), 88 QuantityValue = Convert.ToInt32(item["quantity"]["value"].ToString()), 89 StatusText = item["status"]["text"].ToString(), 90 SaleQuantity = Convert.ToInt32(item["saleQuantity"].ToString()) 91 }; 92 list.Add(model); 93 } 94 95 return list; 96 } 97 98 #endregion 99 100 #region 上架或下架成功后結果分析 101 102 103 /// <summary> 104 /// 獲取提交后的返回狀態 105 /// </summary> 106 /// <returns></returns> 107 public static string GetGoodsResult(string html) 108 { 109 ClearHtml(html); 110 string strPattern = string.Format("{0}\\s*(?<key>.*?),\\s*{1}", Regex.Escape("\"alerts\":"), Regex.Escape("\"icons\":")); 111 var str = RegexMatchHtml(html, strPattern); 112 return ResultByJson(str); 113 } 114 115 /// <summary> 116 /// 提交成功后返回 117 /// </summary> 118 /// <param name="json"></param> 119 /// <returns></returns> 120 public static string ResultByJson(string json) 121 { 122 var jsonObj = (JArray)JsonConvert.DeserializeObject(json); 123 var sub = new StringBuilder(); 124 var i = 0; 125 foreach (JToken item in jsonObj) 126 { 127 if (i == 0) 128 { 129 sub.Append("type:" + item["type"]); 130 sub.Append("\n"); 131 sub.Append("msg:" + item["msg"]); 132 sub.Append("\n"); 133 } 134 else 135 { 136 sub.Append("id:" + item["id"]); 137 sub.Append("--"); 138 sub.Append("type:" + item["type"]); 139 sub.Append("--"); 140 sub.Append("msg:" + item["msg"]); 141 sub.Append("\n"); 142 } 143 i++; 144 } 145 return sub.ToString(); 146 } 147 148 #endregion 149 150 #endregion 151 152 #region 公共部分 153 /// <summary> 154 /// Html過濾 155 /// </summary> 156 /// <param name="html"></param> 157 /// <returns></returns> 158 public static string ClearHtml(string html) 159 { 160 html = html.Replace("\r", ""); 161 html = html.Replace("\n", ""); 162 html = html.Replace("\t", ""); 163 return html; 164 } 165 166 /// <summary> 167 /// 正則替換 168 /// </summary> 169 /// <param name="str">原字符串</param> 170 /// <param name="strPattern">正則表達式</param> 171 /// <param name="strReplace">目標字符串</param> 172 /// <returns>替換完成的字符串</returns> 173 private static string RegexReplaceHtml(string str, string strPattern, string strReplace) 174 { 175 var strPatternHref = strPattern; 176 var regexHref = new Regex(strPatternHref, 177 RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant); 178 if (regexHref.IsMatch(str)) 179 { 180 str = regexHref.Replace(str, strReplace); 181 } 182 return str; 183 } 184 185 /// <summary> 186 /// 正則獲取(單個) 187 /// </summary> 188 /// <param name="str"></param> 189 /// <param name="strRegex">正則表達式</param> 190 /// <param name="key">key名</param> 191 /// <returns>匹配后的key內容</returns> 192 public static string RegexMatchHtml(string str, string strRegex, string key = "key") 193 { 194 var regex = 195 new Regex(strRegex, 196 RegexOptions.IgnoreCase | RegexOptions.Singleline); 197 if (regex.IsMatch(str)) 198 { 199 MatchCollection matchCollection = regex.Matches(str); 200 foreach (Match match in matchCollection) 201 { 202 return match.Groups[key].Value.Trim(); 203 } 204 } 205 return "null"; 206 } 207 208 /// <summary> 209 /// 正則獲取(多個) 210 /// </summary> 211 /// <param name="str"></param> 212 /// <param name="strRegex">正則表達式</param> 213 /// <param name="key">key名</param> 214 /// <returns>匹配后的key內容</returns> 215 public static List<string> RegexMatchHtmlMore(string str, string strRegex, string key = "key") 216 { 217 var list = new List<string>(); 218 var regex = 219 new Regex(strRegex, 220 RegexOptions.IgnoreCase | RegexOptions.Singleline); 221 if (regex.IsMatch(str)) 222 { 223 MatchCollection matchCollection = regex.Matches(str); 224 foreach (Match match in matchCollection) 225 { 226 list.Add(match.Groups[key].Value.Trim()); 227 } 228 } 229 return list; 230 } 231 232 #endregion 233 234 } 235 }