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

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

 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/");
         }

     }
 }

窗体后台代码

模拟京东商城登陆HttpRequest的更多相关文章

  1. python 装饰器模拟京东登陆

    要求: 1.三个页面:主页面(home).书店(book).金融页面(finance)2.有两种登陆方式:主页面和书店页面使用京东账户登陆,金融页面使用微信账户登录2.输入:1 ,进入主页面,以此类推 ...

  2. 京东商城跨域设置Cookie实现SSO单点登陆过程

    可以先看下这边文章:http://blog.chinaunix.net/uid-25508399-id-3431705.html   1.点击首页的登陆按钮跳转到京东的登陆中心https://pass ...

  3. ThinkPHP3.2开发仿京东商城项目实战视频教程

    ThinkPHP3.2仿京东商城视频教程实战课程,ThinkPHP3.2开发大型商城项目实战视频 第一天 1.项目说明 2.时间插件.XSS过滤.在线编辑器使用 3.商品的删除 4.商品的修改完成-一 ...

  4. Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据

    本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...

  5. Android 深入ViewPager补间动画,实现类京东商城首页广告Banner切换效果

    如有转载,请声明出处: 时之沙: http://blog.csdn.net/t12x3456 某天看到京东商城首页的滑动广告的Banner,在流动切换的时候有立体的动画效果,感觉很有意思,然后研究了下 ...

  6. 完美高仿精仿京东商城手机客户端android版源码

    完美高仿精仿京东商城手机客户端android版源码,是从安卓教程网那边转载过来的,这款应用源码非常不错的,也是一个非常优秀的应用源码的,希望能够帮到学习的朋友. _js_op> <igno ...

  7. 商城项目实战 | 1.1 Android 仿京东商城底部布局的选择效果 —— Selector 选择器的实现

    前言 本文为菜鸟窝作者刘婷的连载."商城项目实战"系列来聊聊仿"京东淘宝的购物商城"如何实现. 京东商城的底部布局的选择效果看上去很复杂,其实很简单,这主要是要 ...

  8. 商城项目实战 | 2.1 Android 仿京东商城——自定义 Toolbar (一)

    前言 本文为菜鸟窝作者刘婷的连载."商城项目实战"系列来聊聊仿"京东淘宝的购物商城"如何实现. 现在很多的 APP 里面都有自己的自定义风格,特别是京东商城中自 ...

  9. 商城项目实战 | 2.2 Android 仿京东商城——自定义 Toolbar (二)

    本文为菜鸟窝作者刘婷的连载."商城项目实战"系列来聊聊仿"京东淘宝的购物商城"如何实现. 上一篇文章<商城项目实战 | 2.1 Android 仿京东商城 ...

随机推荐

  1. JAVA-----乱码的处理 乱码的解决方法总结

    为什么说乱码是程序员无法避免的话题呢?这个首先要从编码机制上说起,大家都是中文和英文的编码格式不是一样,解码也是不一样的!工作遇到各种各样的乱码的解决方法总结一下. 对于Java由于默认的编码方式是 ...

  2. 【TopCoder】SRM 680 DIV 2

    1. BearPair之bigDistance1.1 题目概述在 <= 50的字符串中找位置i,j 满足(1) s[i] != s[j];(2) abs(i-j)尽可能大.若不存在返回-1, 否 ...

  3. poj2400Supervisor, Supervisee(KM)

    http://poj.org/problem?id=2400 KM算法http://philoscience.iteye.com/blog/1754498 题意:每个雇主对雇员有个满意度 雇员对雇主有 ...

  4. java.lang.ClassNotFoundException: javax.persistence.EntityListeners

    Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/EntityListene ...

  5. 设置一个POJO的某个属性的默认值

    //月利率private BigDecimal monthRate=new BigDecimal(0);  

  6. LinkedBlockingQueue

    LinkedBlockingQueue是一个基于已链接节点的.范围任意的blocking queue的实现.    此队列按 FIFO(先进先出)排序元素.队列的头部 是在队列中时间最长的元素.队列的 ...

  7. 函数buf_LRU_block_remove_hashed_page

    /******************************************************************//** Takes a block out of the LRU ...

  8. UVa 1639 (期望) Candy

    题意: 两个盒子里各有n颗糖,每天有p的概率从第一个盒子里取一颗糖,1-p的概率从第二个盒子里去一颗糖.直到某一天打开某个盒子忽然发现没糖了,求另一个盒子里剩余糖果数的期望. 分析: 紫书上面已经分析 ...

  9. 关于 tomcat 集群中 session 共享的三种方法

    前两种均需要使用 memcached 或redis 存储 session ,最后一种使用 terracotta 服务器共享. 建议使用 redis,不仅仅因为它可以将缓存的内容持久化,还因为它支持的单 ...

  10. ↗☻【编写可维护的JavaScript #BOOK#】第4章 变量、函数和运算符

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...