利用Winform HttpRequest 模拟登陆京东商城

目前只获取订单信息,可以获取图片等其他信息

模拟京东商城登陆HttpRequest-LMLPHP

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Text;

 namespace HelperLib
 {
     public enum ResponeType
     {
         String,
         File
     }
     /// <summary>
     /// HttpRequest Help
     /// Code By:lvxiaojia
     /// blog:http://www.cnblogs.com/lvxiaojia/
     /// </summary>
     public class RequestHelp
     {
         static CookieContainer cookie = new CookieContainer();
         public static string Post(string url, Dictionary<string, string> postData, string referer = "", string accept = "", string contentType = "", ResponeType type = ResponeType.String, string fileSavePath = "", Action<string> action = null, Func<Dictionary<string, string>> fun = null)
         {
             var result = "";
             //var cookie = new CookieContainer();
             StringBuilder strPostData = new StringBuilder();
             if (postData != null)
             {
                 postData.AsQueryable().ToList().ForEach(a =>
                 {
                     strPostData.AppendFormat("{0}={1}&", a.Key, a.Value);
                 });
             }
             byte[] byteArray = Encoding.UTF8.GetBytes(strPostData.ToString().TrimEnd('&'));

             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

             webRequest.CookieContainer = cookie;

             webRequest.Method = "POST";
             if (string.IsNullOrEmpty(accept))
                 webRequest.Accept = "application/json, text/javascript, */*;";
             else
                 webRequest.Accept = accept;

             if (!string.IsNullOrEmpty(referer))
                 webRequest.Referer = referer;
             if (string.IsNullOrEmpty(contentType))
                 webRequest.ContentType = "application/x-www-form-urlencoded";
             else
                 webRequest.ContentType = contentType;

             )
                 webRequest.ContentLength = byteArray.Length;

             //请求
             Stream newStream = webRequest.GetRequestStream();
             newStream.Write(byteArray, , byteArray.Length);
             newStream.Close();

             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
             var responSteam = response.GetResponseStream();

             if (type == ResponeType.String)
             {
                 StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                 result = strRespon.ReadToEnd();
             }
             else
             {
                 BinaryReader br = new BinaryReader(responSteam);
                 );
                 FileStream fs = new FileStream(fileSavePath, FileMode.OpenOrCreate);
                 fs.Write(byteArr, , byteArr.Length);
                 fs.Dispose();
                 fs.Close();
                 result = "OK";
             }
             if (action != null)
             {
                 action.Invoke(result);
             }
             if (fun != null)
             {
                 Dictionary<string, string> dic = new Dictionary<string, string>();
                 foreach (var item in cookie.GetCookies(webRequest.RequestUri))
                 {
                     var c = item as Cookie;
                     dic.Add(c.Name, c.Value);
                 }
                 fun = () => { return dic; };
             }
             return result;

         }

         public static string Get(string url, Dictionary<string, string> postData=null, string referer = "", Action<string> action = null, Action<Dictionary<string, string>> fun = null)
         {
             var result = "";

             StringBuilder strPostData = new StringBuilder("?");
             if (postData != null)
             {
                 postData.AsQueryable().ToList().ForEach(a =>
                 {
                     strPostData.AppendFormat("{0}={1}&", a.Key, a.Value);
                 });
             }
             )
                 strPostData = strPostData.Clear();
             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + strPostData.ToString().TrimEnd('&'));
             webRequest.CookieContainer = cookie;
             webRequest.Method = "GET";
             webRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*;";
             if (!string.IsNullOrEmpty(referer))
                 webRequest.Referer = referer;
             //请求
             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
             var responSteam = response.GetResponseStream();

             StreamReader strRespon = new StreamReader(responSteam, Encoding.Default);
             result = strRespon.ReadToEnd();

             if (action != null)
             {
                 action.Invoke(result);
             }
             if (fun != null)
             {
                 Dictionary<string, string> dic = new Dictionary<string, string>();
                 foreach (var item in cookie.GetCookies(webRequest.RequestUri))
                 {
                     var c = item as Cookie;
                     dic.Add(c.Name, c.Value);
                 }
                 fun.Invoke(dic);
             }
             return result;

         }

     }
 }

RequestHelp

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Linq;
 using System.Reflection;
 using System.Security.Cryptography;
 using System.Text;

 namespace HelperLib
 {
     /// <summary>
     ///
     /// </summary>
     public class EncodingHelp
     {
         public static string GetMd5Str32(string str)
         {
             MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
             char[] temp = str.ToCharArray();
             byte[] buf = new byte[temp.Length];
             ; i < temp.Length; i++)
             {
                 buf[i] = (byte)temp[i];
             }
             byte[] data = md5Hasher.ComputeHash(buf);
             StringBuilder sBuilder = new StringBuilder();
             ; i < data.Length; i++)
             {
                 sBuilder.Append(data[i].ToString("x2"));
             }
             return sBuilder.ToString();
         }

         public static string GetEnumDescription(Enum value)
         {
             Type enumType = value.GetType();
             string name = Enum.GetName(enumType, value);
             if (name != null)
             {
                 // 获取枚举字段。
                 FieldInfo fieldInfo = enumType.GetField(name);
                 if (fieldInfo != null)
                 {
                     // 获取描述的属性。
                     DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
                         typeof(DescriptionAttribute), false) as DescriptionAttribute;
                     if (attr != null)
                     {
                         return attr.Description;
                     }
                 }
             }
             return null;
         }
     }
 }

EncodingHelp

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Diagnostics;
 using System.Drawing;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Web;
 using System.Windows.Forms;
 using HelperLib;

 namespace SimulationSouGouLogion
 {
     public partial class LoginJD : Form
     {
         public LoginJD()
         {
             InitializeComponent();
         }

         static string loginUrl = "https://passport.jd.com/new/login.aspx";
         static string loginServiceUrl = "http://passport.jd.com/uc/loginService";
         static string loginRefererUrl = "http://passport.jd.com/uc/login?ltype=logout";

         private void button1_Click(object sender, EventArgs e)
         {
             richTextBox1.Text = "";

             RequestHelp.Get(loginUrl, null);

             var login = RequestHelp.Post(loginServiceUrl,
                 new Dictionary<string, string>(){
                 {"uuid","59c439c8-09de-4cce-8293-7a296b0c0dd1"},
                 {"loginname",HttpUtility.UrlEncode(tbUserCode.Text)},
                 {"nloginpwd",HttpUtility.UrlEncode(tbPassword.Text)},
                 {"loginpwd",HttpUtility.UrlEncode(tbPassword.Text)},
                 {"machineNet","machineCpu"},
                 {"machineDisk",""},
                 {"authcode",""}}, loginRefererUrl);

             if (!login.Contains("success"))
             {
                 if (login.ToLower().Contains("pwd"))
                 {
                     MessageBox.Show("密码验证不通过!", "提示");
                     tbPassword.Text = "";
                     tbPassword.Focus();
                     return;
                 }
                 else
                 {
                     MessageBox.Show("登陆失败!", "提示"); return;
                 }
             }

             var dic = new Dictionary<string, string>();
             //获取订单列表
             var orderList = RequestHelp.Get("http://order.jd.com/center/list.action?r=635133982534597500", null, fun: a => dic = a);

             //分析网页HTML
             var regexOrder = Repex(@"<tr id=.{1}track\d+.{1} oty=.{1}\d{1,3}.{1}>.*?</tr>?", orderList);

             //获取每个订单信息
             regexOrder.ForEach(a =>
             {
                 var orderCode = Repex(@"<a name=.{1}orderIdLinks.{1} .*? href=.{1}(.*)'?.{1}>(.*)?</a>?", a);
                 ]);
                 richTextBox1.Text += ] + "\r\n";
                 richTextBox1.Text += ] + "\r\n";
             });

             //获取订单信息
             //var details = RequestHelp.Get("http://jd2008.jd.com/jdhome/CancelOrderInfo.aspx?orderid=502561335&PassKey=28C8E5A477E7B255A72A7A67841D5D13");
         }

         List<string> Repex(string parm, string str)
         {
             List<string> list = new List<string>();
             var regex = new Regex(parm, RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
             var math = regex.Matches(str);
             ) return list;

             foreach (var item in math)
             {
                 var strdetails = (item as Match).Value;

                 list.Add(strdetails);
             }

             return list;

         }
         List<string> Match(string parm, string str)
         {
             List<string> list = new List<string>();
             var math = Regex.Matches(str, parm);
             ) return list;
             list.Add(math[].Result("$1"));
             list.Add(math[].Result("$2"));
             return list;

         }

         private void Form1_Load(object sender, EventArgs e)
         {
             tbPassword.Focus();
         }

         private void blogLink_Click(object sender, EventArgs e)
         {
             Process.Start("http://www.cnblogs.com/lvxiaojia/");
         }

     }
 }

窗体后台代码

05-11 22:50