12306查询车票例子

作者:源码世界时间:2014-03-13分类:程序员碎语评论:0浏览:6090
package com.chenlm.main;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;

import com.google.gson.Gson;

public class SeachThread implements Runnable {

    /**查询参数实体*/
    private QueryPo query;

    private static HttpClient httpClient = null;

    /**车站信息*/
    public static StationNameMem stationNameMem = StationNameMem.getInstance();

    /**读取车站信息,装入内存*/
    static{
        try{

            InputStream in = new BufferedInputStream(new FileInputStream("config/stationName"));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] data = new byte[8192];
            int length = 8192;
            while((length = in.read(data, 0, length)) != -1){
                bos.write(data, 0, length);
            }
            String nameStr = new String(bos.toByteArray(), "UTF-8");

            String[] stations = nameStr.split("@");

            List<Station> stationList = new ArrayList<Station>();
            for(String s : stations){
                if(s != null && s.length() > 0){
                    String[] values = s.split("\\|");
                    if(values != null && values.length == 6){
                        Station station = new Station();
                        station.setName1(values[0]);
                        station.setStationName(values[1]);
                        station.setStationCode(values[2]);
                        station.setQuanPin(values[3]);
                        station.setJianPin(values[4]);
                        stationList.add(station);
                    }
                }
            }
            stationNameMem.setStations(stationList);
        }catch(Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public SeachThread(QueryPo qPo){
        // 指定协议名称和默认的端口号
        Protocol myhttps = new Protocol("https", new MySecureProtocolSocketFactory(), 443);
        // 注册刚才创建的https 协议对象
        Protocol.registerProtocol("https", myhttps);
        httpClient = new HttpClient();
        query = qPo;
    }

    @Override
    public void run(){
        // URL url;
        try{
            // url = new URL(getUrl(query));
            while(true){
                GetMethod pmethod = new GetMethod(getUrl(query));
                httpClient.executeMethod(pmethod);
                String value = pmethod.getResponseBodyAsString();
                print(value);
                Thread.sleep(800);
            }
        }catch(Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 解析返回收据打印
     * @param value
     * @throws IOException
     *
     * @author Chenlm
     * @date 2014-1-24 上午11:21:39
     */
    private synchronized void print(String value) throws IOException{
        Gson son = new Gson();
        Map m = son.fromJson(value, Map.class);
        List l = (List)m.get("data");
        if(l != null && l.size() > 0){
            Date d = new Date();
            System.out.println("共" + l.size() + "条记录" + d.toLocaleString());
            StringBuffer strbuf = new StringBuffer();
            for(int i = 0; i < l.size(); i++){
                strbuf.setLength(0);
                Map lm = (Map)l.get(i);
                Map dto = (Map)lm.get("queryLeftNewDTO");
                String buttonTextInfo = (String)lm.get("buttonTextInfo");

                String station_train_code = (String)dto.get("station_train_code");
                String startStation = (String)dto.get("start_station_name");
                String fromStation = (String)dto.get("from_station_name");
                String endStation = (String)dto.get("end_station_name");
                String toStation = (String)dto.get("to_station_name");

                String startTime = (String)dto.get("start_time");
                String endTime = (String)dto.get("arrive_time");
                strbuf.append("  " + station_train_code);
                strbuf.append(" ").append(startStation).append("-->").append(fromStation).append("-->").append(toStation).append("-->")
                        .append(endStation);
                strbuf.append("  ").append(startTime).append("-").append(endTime);

                String yz = (String)dto.get("yz_num");
                String wz = (String)dto.get("wz_num");
                String yw = (String)dto.get("yw_num");
                String rw = (String)dto.get("rw_num");

                String ypInfo = (String)dto.get("yp_info");
                Integer yzNum = 0;
                Integer wzNum = 0;
                Integer ywNum = 0;
                Integer rwNum = 0;
                if(ypInfo != null && ypInfo.length() == 40){
                    yzNum = Integer.parseInt(ypInfo.substring(27, 27 + 3));
                    wzNum = Integer.parseInt(ypInfo.substring(7, 7 + 3));
                    ywNum = Integer.parseInt(ypInfo.substring(37, 37 + 3));
                    rwNum = Integer.parseInt(ypInfo.substring(17, 17 + 3));
                }

                strbuf.append("  |").append("硬座:").append(yz.equals("无")? yz : yzNum);
                strbuf.append("  |").append("无座:").append(wz.equals("无") ? yz : wzNum);
                strbuf.append("  |").append("硬卧:").append(yw.equals("无") ? yz : ywNum);
                strbuf.append("  |").append("软卧:").append(rw.equals("无") ? yz : rwNum);

                strbuf.append("      " + buttonTextInfo);
                String cheCi = query.getCheCi().trim().toUpperCase();
                if(cheCi.length() > 0){
                String[] cs = cheCi.split(",");
                
                   if(cs != null && cs.length > 0){
                       for(String  c : cs){
                           if(c.trim().toUpperCase().equals(station_train_code.toUpperCase())){
                               System.out.println(strbuf.toString());
   
                           }
                       }
                   }
                }
                else {
                    System.out.println(strbuf.toString());

                }
            }
        }else{
            System.out.println("未查询到结果");
        }
    }

    private String getUrl(QueryPo qPo){
        StringBuilder s = new StringBuilder();
        s.append(qPo.getUrl());
        s.append("?leftTicketDTO.train_date=");
        s.append(qPo.getDate());
        s.append("&leftTicketDTO.from_station=");
        s.append(qPo.getFromStation());
        s.append("&leftTicketDTO.to_station=");
        s.append(qPo.getToStation());
        s.append("&purpose_codes=ADULT");
        return s.toString();
    }
}
标签:Java  
返回顶部
分享按钮