1. 程式人生 > >java抓取資料包查詢12306餘票資訊

java抓取資料包查詢12306餘票資訊

最近專案比較閒,閒來無事,參照網上的程式碼實現了一下抓取12306資料包查詢餘票的程式碼,

需要的jar包需要全部包含到專案下,程式碼測試OK,具體程式碼如下:



import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;


import javax.net.ssl.HttpsURLConnection;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class TestTmp {
/**
 * @params args
 * @return void
 */
public static void main(String[] args) throws Exception {

//執行該程式碼前需要生成證書檔案放到jre的security目錄下,具體操作參照
//http://blog.csdn.net/faye0412/article/details/6883879/

//站點庫程式碼參照:https://kyfw.12306.cn/otn/resources/js/framework/station_name.js

String trainDate = "2016-11-30";
String fromStation ="XAY";
String toStation = "SHH";
getHttp(trainDate,fromStation,toStation);
}


/**
 * @param trainDate  乘車日期
 * @param fromStation 起點站程式碼
 * @param toStation 終點站程式碼
 * @return void 無
 * @author liuyong
 * @serialData 2016年11月30日12:55:58
 */
public static void getHttp(String trainDate,String fromStation,String toStation) throws Exception {

JSONObject jsonObject = null;
JSONArray  jsonArray = null;
URL reqURL = new URL(
"https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date="+trainDate+"&leftTicketDTO.from_station="+fromStation+"&leftTicketDTO.to_station="+toStation+"&purpose_codes=ADULT"); // 
HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();
InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());

String jsonstring = "";


int respInt = insr.read();
while (respInt != -1) {

jsonstring += String.valueOf((char) respInt);
//System.out.print(((char) respInt));
respInt = insr.read();


}
jsonObject = JSONObject.fromObject(jsonstring);
//System.out.println(formatJson(jsonstring));

//System.out.println(jsonObject.get("data"));
jsonArray = JSONArray.fromObject(jsonObject.get("data"));

for(int i = 0 ; i < jsonArray.size(); i++){

JSONObject  tmpJsonBoj = jsonArray.getJSONObject(i);
JSONObject finalJsonObj = (JSONObject) tmpJsonBoj.get("queryLeftNewDTO");
String trainCode = finalJsonObj.getString("station_train_code");
String startStation  = finalJsonObj.getString("from_station_name");
String endStation = finalJsonObj.getString("to_station_name");
String satrtTime = finalJsonObj.getString("start_time");
String arrivalTime = finalJsonObj.getString("arrive_time");
String lishi= finalJsonObj.getString("lishi");
String canWebBuy = finalJsonObj.getString("canWebBuy");

//System.out.print("車次:" + trainCode);
System.out.printf("車次:");
System.out.printf("%-6s",trainCode);
System.out.printf("出發站:");
System.out.printf("%-10s",startStation);
System.out.printf("終點站:");
System.out.printf("%-10s",endStation);
System.out.printf("出發時間:");
System.out.printf("%-6s",satrtTime);
System.out.printf("到達時間:");
System.out.printf("%-6s",arrivalTime);
System.out.printf("歷時:");
System.out.printf("%-6s",lishi);
System.out.printf("是否網購:");
System.out.printf("%-4s",canWebBuy);
System.out.println();
//剩下輸出資訊根據需要自己找吧
}

}

/**
 * 格式化json字串,參照別人的程式碼,暫時沒有用到
 * @param jsonStr
 * @return
 * @author  
 * @Date 
 */
    public static String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr)) return "";
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '{':
                case '[':
                    sb.append(current);
                    sb.append('\n');
                    indent++;
                    addIndentBlank(sb, indent);
                    break;
                case '}':
                case ']':
                    sb.append('\n');
                    indent--;
                    addIndentBlank(sb, indent);
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\') {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }


        return sb.toString();
    }


    /**
     * 新增space
     * @param 
     * @param 
     * @author   
     * @Date   
     */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }


}