模拟京东商城登陆HttpRequest

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

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

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Text;
  7 
  8 namespace HelperLib
  9 {
 10     public enum ResponeType
 11     {
 12         String,
 13         File
 14     }
 15     /// <summary>
 16     /// HttpRequest Help
 17     /// Code By:lvxiaojia
 18     /// blog:http://www.cnblogs.com/lvxiaojia/
 19     /// </summary>
 20     public class RequestHelp
 21     {
 22         static CookieContainer cookie = new CookieContainer();
 23         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)
 24         {
 25             var result = "";
 26             //var cookie = new CookieContainer();
 27             StringBuilder strPostData = new StringBuilder();
 28             if (postData != null)
 29             {
 30                 postData.AsQueryable().ToList().ForEach(a =>
 31                 {
 32                     strPostData.AppendFormat("{0}={1}&", a.Key, a.Value);
 33                 });
 34             }            
 35             byte[] byteArray = Encoding.UTF8.GetBytes(strPostData.ToString().TrimEnd('&'));
 36 
 37             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
 38 
 39             webRequest.CookieContainer = cookie;
 40 
 41             webRequest.Method = "POST";
 42             if (string.IsNullOrEmpty(accept))
 43                 webRequest.Accept = "application/json, text/javascript, */*;";
 44             else
 45                 webRequest.Accept = accept;
 46 
 47             if (!string.IsNullOrEmpty(referer))
 48                 webRequest.Referer = referer;
 49             if (string.IsNullOrEmpty(contentType))
 50                 webRequest.ContentType = "application/x-www-form-urlencoded";
 51             else
 52                 webRequest.ContentType = contentType;
 53 
 54             if (strPostData.Length > 0)
 55                 webRequest.ContentLength = byteArray.Length;
 56 
 57             //请求
 58             Stream newStream = webRequest.GetRequestStream();
 59             newStream.Write(byteArray, 0, byteArray.Length);
 60             newStream.Close();
 61 
 62             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
 63             var responSteam = response.GetResponseStream();
 64 
 65             if (type == ResponeType.String)
 66             {
 67                 StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
 68                 result = strRespon.ReadToEnd();
 69             }
 70             else
 71             {
 72                 BinaryReader br = new BinaryReader(responSteam);
 73                 byte[] byteArr = br.ReadBytes(200000);
 74                 FileStream fs = new FileStream(fileSavePath, FileMode.OpenOrCreate);
 75                 fs.Write(byteArr, 0, byteArr.Length);
 76                 fs.Dispose();
 77                 fs.Close();
 78                 result = "OK";
 79             }
 80             if (action != null)
 81             {
 82                 action.Invoke(result);
 83             }
 84             if (fun != null)
 85             {
 86                 Dictionary<string, string> dic = new Dictionary<string, string>();
 87                 foreach (var item in cookie.GetCookies(webRequest.RequestUri))
 88                 {
 89                     var c = item as Cookie;
 90                     dic.Add(c.Name, c.Value);
 91                 }
 92                 fun = () => { return dic; };
 93             }
 94             return result;
 95 
 96         }
 97 
 98 
 99         public static string Get(string url, Dictionary<string, string> postData=null, string referer = "", Action<string> action = null, Action<Dictionary<string, string>> fun = null)
100         {
101             var result = "";
102             
103             StringBuilder strPostData = new StringBuilder("?");
104             if (postData != null)
105             {
106                 postData.AsQueryable().ToList().ForEach(a =>
107                 {
108                     strPostData.AppendFormat("{0}={1}&", a.Key, a.Value);
109                 });
110             }
111             if (strPostData.Length == 1)
112                 strPostData = strPostData.Clear();
113             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + strPostData.ToString().TrimEnd('&'));
114             webRequest.CookieContainer = cookie;
115             webRequest.Method = "GET";
116             webRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*;";
117             if (!string.IsNullOrEmpty(referer))
118                 webRequest.Referer = referer;
119             //请求
120             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
121             var responSteam = response.GetResponseStream();
122 
123             StreamReader strRespon = new StreamReader(responSteam, Encoding.Default);
124             result = strRespon.ReadToEnd();
125 
126             if (action != null)
127             {
128                 action.Invoke(result);
129             }
130             if (fun != null)
131             {
132                 Dictionary<string, string> dic = new Dictionary<string, string>();
133                 foreach (var item in cookie.GetCookies(webRequest.RequestUri))
134                 {
135                     var c = item as Cookie;
136                     dic.Add(c.Name, c.Value);
137                 }
138                 fun.Invoke(dic);
139             }
140             return result;
141 
142         }
143 
144     }
145 }
RequestHelp
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Linq;
 5 using System.Reflection;
 6 using System.Security.Cryptography;
 7 using System.Text;
 8 
 9 namespace HelperLib
10 {
11     /// <summary>
12     /// 
13     /// </summary>
14     public class EncodingHelp
15     {
16         public static string GetMd5Str32(string str)
17         {
18             MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
19             char[] temp = str.ToCharArray();
20             byte[] buf = new byte[temp.Length];
21             for (int i = 0; i < temp.Length; i++)
22             {
23                 buf[i] = (byte)temp[i];
24             }
25             byte[] data = md5Hasher.ComputeHash(buf);
26             StringBuilder sBuilder = new StringBuilder();
27             for (int i = 0; i < data.Length; i++)
28             {
29                 sBuilder.Append(data[i].ToString("x2"));
30             }
31             return sBuilder.ToString();
32         }
33 
34         public static string GetEnumDescription(Enum value)
35         {
36             Type enumType = value.GetType();
37             string name = Enum.GetName(enumType, value);
38             if (name != null)
39             {
40                 // 获取枚举字段。
41                 FieldInfo fieldInfo = enumType.GetField(name);
42                 if (fieldInfo != null)
43                 {
44                     // 获取描述的属性。
45                     DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
46                         typeof(DescriptionAttribute), false) as DescriptionAttribute;
47                     if (attr != null)
48                     {
49                         return attr.Description;
50                     }
51                 }
52             }
53             return null;
54         }
55     }
56 }
EncodingHelp
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Diagnostics;
  6 using System.Drawing;
  7 using System.IO;
  8 using System.Linq;
  9 using System.Net;
 10 using System.Text;
 11 using System.Text.RegularExpressions;
 12 using System.Web;
 13 using System.Windows.Forms;
 14 using HelperLib;
 15 
 16 namespace SimulationSouGouLogion
 17 {
 18     public partial class LoginJD : Form
 19     {
 20         public LoginJD()
 21         {
 22             InitializeComponent();
 23         }
 24 
 25         static string loginUrl = "https://passport.jd.com/new/login.aspx";
 26         static string loginServiceUrl = "http://passport.jd.com/uc/loginService";
 27         static string loginRefererUrl = "http://passport.jd.com/uc/login?ltype=logout";
 28 
 29         private void button1_Click(object sender, EventArgs e)
 30         {
 31             richTextBox1.Text = "";
 32 
 33             RequestHelp.Get(loginUrl, null);
 34 
 35             var login = RequestHelp.Post(loginServiceUrl,
 36                 new Dictionary<string, string>(){
 37                 {"uuid","59c439c8-09de-4cce-8293-7a296b0c0dd1"},
 38                 {"loginname",HttpUtility.UrlEncode(tbUserCode.Text)},
 39                 {"nloginpwd",HttpUtility.UrlEncode(tbPassword.Text)},
 40                 {"loginpwd",HttpUtility.UrlEncode(tbPassword.Text)},
 41                 {"machineNet","machineCpu"},
 42                 {"machineDisk",""},
 43                 {"authcode",""}}, loginRefererUrl);
 44 
 45             if (!login.Contains("success"))
 46             {
 47                 if (login.ToLower().Contains("pwd"))
 48                 {
 49                     MessageBox.Show("密码验证不通过!", "提示");
 50                     tbPassword.Text = "";
 51                     tbPassword.Focus();
 52                     return;
 53                 }
 54                 else
 55                 {
 56                     MessageBox.Show("登陆失败!", "提示"); return;
 57                 }
 58             }
 59 
 60 
 61             var dic = new Dictionary<string, string>();
 62             //获取订单列表
 63             var orderList = RequestHelp.Get("http://order.jd.com/center/list.action?r=635133982534597500", null, fun: a => dic = a);
 64 
 65             //分析网页HTML
 66             var regexOrder = Repex(@"<tr id=.{1}track\d+.{1} oty=.{1}\d{1,3}.{1}>.*?</tr>?", orderList);
 67 
 68             //获取每个订单信息
 69             regexOrder.ForEach(a =>
 70             {
 71                 var orderCode = Repex(@"<a name=.{1}orderIdLinks.{1} .*? href=.{1}(.*)'?.{1}>(.*)?</a>?", a);
 72                 var order = Match(@"<a name='orderIdLinks' .*? href='(.*)?' clstag=.*>(.*)</a>", orderCode[0]);
 73                 richTextBox1.Text += "订单号:" + order[1] + "\r\n";
 74                 richTextBox1.Text += "订单详情地址:" + order[0] + "\r\n";
 75             });
 76 
 77             //获取订单信息
 78             //var details = RequestHelp.Get("http://jd2008.jd.com/jdhome/CancelOrderInfo.aspx?orderid=502561335&PassKey=28C8E5A477E7B255A72A7A67841D5D13");
 79         }
 80 
 81         List<string> Repex(string parm, string str)
 82         {
 83             List<string> list = new List<string>();
 84             var regex = new Regex(parm, RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
 85             var math = regex.Matches(str);
 86             if (math.Count < 0) return list;
 87 
 88             foreach (var item in math)
 89             {
 90                 var strdetails = (item as Match).Value;
 91 
 92                 list.Add(strdetails);
 93             }
 94 
 95             return list;
 96 
 97         }
 98         List<string> Match(string parm, string str)
 99         {
100             List<string> list = new List<string>();
101             var math = Regex.Matches(str, parm);
102             if (math.Count < 0) return list;
103             list.Add(math[0].Result("$1"));
104             list.Add(math[0].Result("$2"));
105             return list;
106 
107         }
108 
109         private void Form1_Load(object sender, EventArgs e)
110         {
111             tbPassword.Focus();
112         }
113 
114         private void blogLink_Click(object sender, EventArgs e)
115         {
116             Process.Start("http://www.cnblogs.com/lvxiaojia/");
117         }
118 
119     }
120 }
窗体后台代码

 

转载于:https://www.cnblogs.com/lvxiaojia/p/3292689.html

# JD_AutoBuy ## 京东抢购 Python爬虫,自动登录京东网站,查询商品库存,价格,显示购物车详情等。 可以指定抢购商品,自动购买下单,然后手动去京东付款就行。 ## chang log + 2017-03-30 实现二维码扫码登陆 ## 运行环境 Python 2.7 ## 第三方库 - [Requests][1]: 简单好用,功能强大的Http请求库 - [beautifulsoup4][2]: HTML文档格式化及便签选择器 ## 环境配置 ``` Python pip install requests pip install beautifulsoup4 ``` ## 使用帮助 ``` cmd > python scraper-jd.py -h usage: scraper-jd.py [-h] [-u USERNAME] [-p PASSWORD] [-g GOOD] [-c COUNT] [-w WAIT] [-f] [-s] Simulate to login Jing Dong, and buy sepecified good optional arguments: -h, --help show this help message and exit -u USERNAME, --username USERNAME Jing Dong login user name -p PASSWORD, --password PASSWORD Jing Dong login user password -g GOOD, --good GOOD Jing Dong good ID -c COUNT, --count COUNT The count to buy -w WAIT, --wait WAIT Flush time interval, unit MS -f, --flush Continue flash if good out of stock -s, --submit Submit the order to Jing Dong ``` ## 实例输出 ``` cmd +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:01 2017 > 请打开京东手机客户端,准备扫码登陆: 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 202 : 请手机客户端确认登录 200 : BADACIFYhf6fakfHvjiYTlwGzSp4EjFATN3Xw1ePR1hITtw0 登陆成功 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:28 2017 > 商品详情 编号:3133857 库存:现货 价格:6399.00 名称:Apple iPhone 7 Plus (A1661) 128G 黑色 移动联通电信4G手机 链接:http://cart.jd.com/gate.action?pid=3133857&pcount=1&ptype=1 商品已成功加入购物车! 购买数量:3133857 > 1 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:30 2017 > 购物车明细 购买 数量 价格 总价 商品 Y 1 6399.00 6399.00 Apple iPhone 7 Plus (A1661) 128G 黑色 移动联通电信4G手机 总数: 1 总额: 6399.00 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:30 2017 > 订单详情 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ ... ``` ## 注 代码仅供学习之用,京东网页不断变化,代
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值