栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现京东秒杀功能分享 京东秒杀软件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现京东秒杀功能分享 京东秒杀软件

简单介绍下功能

1.每隔一段时间(比如1分钟)在京东手机每日一秒杀页面提取产品(手机)链接。
http://sale.360buy.com/act/8VTHFGr10CjMDyZ.html#01
2.根据提取到得产品链接给后台发送数据,以便获取产品价格,描述,折扣,库存(是否有货)等信息。
3.根据得到的信息,进行判断。

若符合条件自动调用浏览器(前提是chrome加入环境变量,或者改代码将浏览器.exe路径加入代码,修改程序)打开产品订购页面。
4.其实也就解决了一个问题:不用自己频繁的刷新网页了,不用自己查看;
登陆,提交订单还得浏览器解决(貌似这几个功能点比较复杂,没做处理)

程序做的不太完善:
运行前需要修改几个地方:
1.环境变量:chrome 加入浏览器变量,以便调用。。或者自己修改源代码用其它方式打开。
2.活动中每个产品的价格信息需要设置。这个比较不好,必须修改源代码。
修改的地方在filter()这个函数里。
3.另外一个需要修改的地方是
hasStore(String skuidkey)

address="http://price.360buy.com/stocksoa/StockHandler.ashx?callback=getProvinceStockCallback&type=pcastock&skuid="+skuidkey+"&provinceid=1&cityid=2800&areaid=2850";
这个地方的cityid=2800&areaid=...地里位置信息。这个没做处理。需要从手机产品页自己搞出来。
其实也比较简单。chrome+F12 ,修改“城市”,区域等信息后,会看到一个get请求发送到后台,这个链接里面包含了需要的信息。(http://price.360buy.com/stocksoa/StockHandler.ashx?callback=getProvinceStockCallback&type=pcastock&skuid=64EBD0F20F593D95C72C6EED59B64658&provinceid=1&cityid=2805&areaid=2854)适当修改。

Util.java

复制代码 代码如下:
package view.Util;

import java.util.ArrayList;

public class Util {
 public static void print(Object o){
  System.out.print(o);
 }
 public static void println(Object o){
  if(null==o)
   System.out.println();
  else
  System.out.println(o);
 }
 public static ArrayList toArrayList(int[] ints){
  if(ints.length==0)
  return null;
  ArrayList al=new ArrayList();
  for(int i=0;i   al.add(ints[i]);
  }
  return al;
 }
}

Miaosha360buy.java

复制代码 代码如下:
package jingdong;

public class Miaosha360buy {
 java.util.concurrent.CountDownLatch t= new java.util.concurrent.CountDownLatch(1);

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println(Thread.currentThread().getName() + "开始");
  Miaosha360buy ms360=new Miaosha360buy();
  new ThreadOne360buy(ms360.t).start();
  while(true){
   try {
    ms360.t.await();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    Thread.sleep(1000*60);//间隔1分钟调用一次?
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   ms360.t=new java.util.concurrent.CountDownLatch(1);
   new ThreadOne360buy(ms360.t).start();
   System.out.println("New Tread in while..");
  }
 }

}

Miaosha360buy.java

复制代码 代码如下:
package jingdong;

public class Miaosha360buy {
 java.util.concurrent.CountDownLatch t= new java.util.concurrent.CountDownLatch(1);

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println(Thread.currentThread().getName() + "开始");
  Miaosha360buy ms360=new Miaosha360buy();
  new ThreadOne360buy(ms360.t).start();
  while(true){
   try {
    ms360.t.await();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    Thread.sleep(1000*60);//间隔1分钟调用一次?
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   ms360.t=new java.util.concurrent.CountDownLatch(1);
   new ThreadOne360buy(ms360.t).start();
   System.out.println("New Tread in while..");
  }
 }

}

ThreadOne360buy.java

复制代码 代码如下:
package jingdong;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import view.Util.Util;

public class ThreadOne360buy extends Thread{
 java.util.concurrent.CountDownLatch c;
 ArrayList al;//记录秒杀产品页面
 float price=0.0f;//商品价格
 float discount=0.0f;//商品折扣

 //用于保存线程信息,在这个项目里用处不大
 private static List runningThreads = new ArrayList();

 //这个是一个计数器(不太会用,线程这方面一直感觉是比较复杂的)
 public ThreadOne360buy(java.util.concurrent.CountDownLatch c) {
  this.c=c;
 }

 @Override
 public void run() {
  regist(this);// 线程开始时注册
  // 打印开始标记
  System.out.println(Thread.currentThread().getName() + "开始...");
  try {
   //抓取京东手机秒杀页面
   this.getMessage("http://sale.360buy.com/act/8VTHFGr10CjMDyZ.html#01");

  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   c.countDown();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   c.countDown();
  }
  c.countDown();
  unRegist(this);// 线程结束时取消注册
  // 打印结束标记
  System.out.println(Thread.currentThread().getName() + "结束.");
 }

 public void regist(Thread t) {
  synchronized (runningThreads) {
   runningThreads.add(t);
  }
 }

 public void unRegist(Thread t) {
  synchronized (runningThreads) {
   runningThreads.remove(t);
  }
 }

 public static boolean hasThreadRunning() {
  // 通过判断runningThreads是否为空就能知道是否还有线程未执行完
  return (runningThreads.size() > 0);
 }
 
 public void getMessage(String url) throws ClientProtocolException, IOException{
  al=getMainUrl(down(url));

  Util.println(al);
  if(al.size()==0){
   c.countDown();
   System.exit(0);
   return;
  }

  for(int i=0;i   StringBuffer sb=new StringBuffer();
   StringBuffer openUrl = new StringBuffer();
   openUrl.append("http://www.360buy.com/product/");
   openUrl.append(al.get(i).toString().subSequence(al.get(i).toString().lastIndexOf('/')+1, al.get(i).toString().lastIndexOf('.')));
   openUrl.append(".html");
//   557673
   sb.append("http://d.360buy.com/fittingInfo/get?skuId=");
   sb.append(al.get(i).toString().subSequence(al.get(i).toString().lastIndexOf('/')+1, al.get(i).toString().lastIndexOf('.')));
   sb.append("&callback=Recommend.cbRecoFittings");
   Util.println(sb.toString());
   //map中保存的是产品name,price,折扣信息
   Util.println("Al("+i+") down:"+sb.toString());
   HashMap hm=parseProduct(down(sb.toString()));
   //用来匹配价格信息。匹配库存信息
   filter(hm,openUrl.toString());//过滤价格,如果条件符合就打开浏览器
  }
 }
 
 public void filter(HashMap hm,String url){//url既是产品页面
//  view.Util.oenCMD.openWinExe(null,url);
//  是不是应该先查看库存?
  String skuidkey=parseSkuidkey(url);
  if(!hasStore(skuidkey)){
   Util.println("-------------------------------------");
   Util.println("没有库存了!");
   Util.println("-------------------------------------");
   //减掉计数,以便主线程判断
   c.countDown();
   //应该结束子线程哦?
   return;
  }

  if(hm.get("skuid").equals("201602")){//判断//摩托罗拉skuid=201602
   //这里的价格是写死了,运行前得改过来才行。
   this.setPrice(499.0f);
   //是不是应该打开控制台?
   if(Float.parseFloat(hm.get("price"))<=this.getPrice()){
    view.Util.oenCMD.openWinExe(null,url);
   }
  }else if(hm.get("skuid").equals("675647")){//天语skuid=675647
//   //这里的价格是写死了,运行前得改过来才行。
//   this.setPrice(699.0f);
//   //是不是应该打开控制台?
//   if(Float.parseFloat(hm.get("price"))<=this.getPrice()){
//    view.Util.oenCMD.openWinExe(null,url);
//   }
  }

 }
 
 public static HashMap parseProduct(document doc){
  String text=doc.text();
  String docc=text.substring(text.indexOf("master")+9,text.indexOf("fittings")-3).replaceAll("[\s]", "");
  String[] ss=docc.split(",");
  HashMap hm=new HashMap();
  for(String it: ss){
   String string=it.replaceAll(""", "");
   if(string.contains("\u"))
   string=unicodeDecode(string);

   String[] str=string.split(":");
   hm.put(str[0], str[1]);
  }
  Util.println(hm);
  return hm;
 }
 
 public static String unicodeDecode(String it){//有个缺点,就是前面的字符无法去掉
  Util.println(it);
  String regex="(\\u[0-9a-f]{4})";
  Pattern pt= Pattern.compile(regex);
  Matcher mc;
  StringBuffer sb;
  StringBuffer sba=new StringBuffer();
  mc=pt.matcher(it);
  while(mc.find()){
   sb=new StringBuffer();
    mc.appendReplacement(sba,sb.append((char )Integer.parseInt((mc.group(1).substring(2)), 16)).toString());
  }
  return sba.toString();
 }
 
 public static document down(String url) throws ClientProtocolException, IOException{
  document doc = null;
  DefaultHttpClient httpClient=new DefaultHttpClient();
  Util.println("DownLoad:"+url);
  HttpGet get=new HttpGet(url);
  HttpResponse response;
  response = httpClient.execute(get);
  HttpEntity entity = response.getEntity();
  doc = Jsoup.parse(entity.getContent(), "utf-8","");
  //释放资源
  EntityUtils.consume(entity);
  //关闭连接
  httpClient.getConnectionManager().shutdown();
  return doc;
 }
 
 public static document down(String url,String code) throws ClientProtocolException, IOException{
  document doc = null;
  DefaultHttpClient httpClient=new DefaultHttpClient();
  Util.println("DownLoad:"+url);
  HttpGet get=new HttpGet(url);
  HttpResponse response;
  response = httpClient.execute(get);
  HttpEntity entity = response.getEntity();
  doc = Jsoup.parse(entity.getContent(), code,"");
  //释放资源
  EntityUtils.consume(entity);
  //关闭连接
  httpClient.getConnectionManager().shutdown();
  return doc;
 }
 
 public static ArrayList getMainUrl(document doc){
  if(doc.equals("")||doc==null)
   return null;
  try {
   Thread.sleep(50);
  } catch (InterruptedException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  ArrayList urls=new ArrayList();
  String rule="map[name=Map] >area[href~=product]";
  
  Elements elements=doc.select(rule);
  for (Element e : elements) {
//   Util.println(e.absUrl("abs:href"));
   urls.add(e.absUrl("abs:href"));
  }
  return urls;
 }
 
 public static String parseSkuidkey(String url){
  document doc=null;
  try {
   doc=down(url,"gb2312");
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
//  Util.println(doc.select("script"));
  String text = null;
  for(Element e : doc.select("script")){
   if(e.data().contains("skuidkey:")){
    text=e.data();
    break;
   }
  }
  //skuidkey:'7D45919EA8242511DAA5CC7C6D7B351C'
  text=text.substring(text.indexOf("skuidkey:")+10, text.indexOf("skuidkey:")+42);
  Util.println("---------------------------------");
  Util.println(text);
  return text;
 }
 
 public static boolean hasStore(String skuidkey){//这个地方没有处理,直接提取浏览器中的信息
  String address = null;
  boolean hasStore=false;
  if(skuidkey!=null && !"".equals(skuidkey))
  address="http://price.360buy.com/stocksoa/StockHandler.ashx?callback=getProvinceStockCallback&type=pcastock&skuid="+skuidkey+"&provinceid=1&cityid=2800&areaid=2850";
  else{
   Util.println("解析skuidkey错误");
  }
  try {
   if(parseStore(down(address))){
    hasStore=true;
   }
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return hasStore;
 }

 
 public static boolean parseStore(document doc){
  String text=doc.text();
  String docc=text.substring(text.indexOf("-")-1,text.lastIndexOf(",")-1);
  Util.println(docc);
  String[] store=docc.split("-");
  if(store[1].equals("34") || store[1].equals("18")){
   //无货
   Util.println("此地无货");
   return false;
  }else if(store[1].equals("33") || store[1].equals("5")){
   //现货
   Util.println("此地现货");
   return true;
  }
  Util.println(store[1]);
  return false;
 }
 //几个bean方法
 public float getPrice() {
  return price;
 }
 public void setPrice(float price) {
  this.price = price;
 }
 public float getDiscount() {
  return discount;
 }
 public void setDiscount(float discount) {
  this.discount = discount;
 }
 

}

oenCMD.java

复制代码 代码如下:
package view.Util;

public class oenCMD {
// public static void main(String[] args) {
////    openWinExe(null);
//    openExe(null,"http://www.baidu.com");
//    }
    //用 Java 调用windows系统的exe文件,比如notepad,calc之类
    public static void openWinExe(String command,String url) {
     if(command==null ||command.equals("")){
      command = "chrome "+url;
     }
    Runtime rn = Runtime.getRuntime();
    Process p = null;
    try {

    p = rn.exec(command);
    } catch (Exception e) {
    System.out.println("Error win exec!");
    }
    }
    //调用其他的可执行文件,例如:自己制作的exe,或是 下载 安装的软件.
    public static void openExe(String pathAndName,String url) {
     if(pathAndName==null || pathAndName.equals("")){
      pathAndName="C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe";
     }
     if(url!=null && !url.equals("")){
      pathAndName+=" ";
      pathAndName+=url;
     }
    Runtime rn = Runtime.getRuntime();
    Process p = null;
    try {
    p = rn.exec(pathAndName);
    } catch (Exception e) {
    System.out.println("Error exec!");
    }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152541.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号