1. 程式人生 > >新手寫的一個12306刷票工具

新手寫的一個12306刷票工具

本來是去年打算寫的一個12306的刷票工具,但是一直拖著沒完成。過完年才搞好。其實也不算寫好,只是感覺都過完年了這個東西都沒多大意義,在說各大網站上都有這個功能。但就當記錄一下吧。

剛開始寫的時候困擾我的其實不是買票的流程,而是如何保持一12306網站的會話,之前在公司做專案的時候一直都是在理論上的,沒有真正的接觸過網站保持一個session是怎麼回事,為此我還特地回去複習了一下這方面的東西,真正感覺到讀萬卷書不如行萬里路。之前一個老鳥跟我過:“這些你不需要現在懂,等你寫多了,自然就懂了”

jar包下載連線:https://pan.baidu.com/s/1Btla6KggGXWml168Er0GAQ

好了開始

獲取驗證圖片,至於這個圖片的驗證數值就是每張圖片的座標。

https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.8863164146128835

引數前面的都是固定的,後面的隨機數;


驗證連線,https://kyfw.12306.cn/passport/captcha/captcha-check

至於這個圖片的驗證數值就是每張圖片的座標。


登入的連結

https://kyfw.12306.cn/passport/web/login


驗證碼和使用者密碼驗證完成之後,這裡還有一個坑就是下面的幾個連結。也要訪問一下。

https://kyfw.12306.cn/passport/web/auth/uamtk     這個連結要獲取 apptk這個值用於下面的請求;

https://kyfw.12306.cn/otn/uamauthclient


到了這裡登入就OK了;

查票的連線,這裡經常會出現查不到東西,不知道是我這邊的網路問題還其他原因,這樣要做好異常處理。

https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2018-01-24&leftTicketDTO.from_station=GZQ&leftTicketDTO.to_station=EFG&purpose_codes=ADULT


這裡的話有就有些欄位要根據車次資訊用來對。其中一個是車站資訊在js檔案中獲取的。



下一個請求是 https://kyfw.12306.cn/otn/login/checkUser,這個應該是檢查使用者,如果前面做好了登入的話這裡沒有必要模擬,我感覺;

提交訂單請求

https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest,其中的secretStr這個欄位就是前面的車次資訊;其他的都很簡單,稍微看一下都能懂。


再來就是https://kyfw.12306.cn/otn/confirmPassenger/initDc這個請求:很重要裡面有兩個字串是下面請求必須要的;我這裡是使用把整個頁面弄下來然後用正則表達扣出那幾個字元;

REPEAT_SUBMIT_TOKEN

key_check_isChange

就是這兩個東西。


再來就是這個https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs。獲取人員資訊的話我感覺可以在前面登入哪裡也可以獲取到人員資訊。但是我還是重新獲取了一遍。


在下一個請求,

https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo

欄位資訊基本上都是根據上面車次資訊對應出來的。需要仔細的看一下車次資訊。


再下一個請求 https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount,其中就是leftTicket欄位需要用車次資訊中欄位進行UrlEncode編碼一下。其他正常搞。


在下一個連線 https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue, 這裡其中就是key_check_isChange欄位要通過上面的initDOC獲取。其他的都正常拼接。


在下一個連線 

https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random=1516711514491&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=bfadc574d156203cadbb5eb5fe4b0030

其中的random是系統時間,獲取就是當放回值 waitCount=0,waitTime=-1,orderId=E685687770是這些值的時候就可以繼續下一個連線。順便把orderId用到下一個請求


在下一個請求 

https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue


這個最核心的方法:

package com.text.cores;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.swing.JTextPane;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.text.utils.MyDateUtil;
import com.text.utils.MyKeepLineHttpUtil;


/**
 * @author liuyh��
 * @date 2017��12��20��--����1:55:24��
 */




public class Code {


private MyKeepLineHttpUtil myKeepLineHttpUtil = new MyKeepLineHttpUtil();
private JSONObject stationName = new JSONObject();
private JSONArray passengerInfo = new JSONArray();
private JTextPane logInfo;



public JSONArray getPassengerInfo() {
return this.passengerInfo;
}


/**
* 設定車站名稱;
*/
private void setStationName(){
InputStream resource = Code.class.getClassLoader().getResourceAsStream("resource/station_name.txt");
InputStreamReader in = null;
String str = "";
try {
in = new InputStreamReader(resource, "GBK");
char[] readvalues = new char[1024];
int readlength;
while((readlength = in.read(readvalues)) != -1){
for(int i = 0; i < readvalues.length; i ++){
str += readvalues[i];
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] split = str.split("@");
for(int i = 0; i < split.length; i++){
String[] split2 = split[i].split("\\|");
this.stationName.put(split2[1], split2[2]);
}
System.out.println(this.stationName.toString());
}

/**
* 使用者登入;
* @param userName
* @param password
* @param answer
* @return
*/
public String login(String userName, String password, String answer){
String resultUserName = "";
if(!loginInit()){
return "error";
}
JSONObject json = null;
json = chenkLoginState();
if(json.getInt("result_code") == 0){
System.out.println("已經登入");
return "success";
}
String validationURL = "https://kyfw.12306.cn/passport/captcha/captcha-check";
Map<String, String> validationMap = new HashMap<>();

validationMap.put("answer", answer);
validationMap.put("login_site", "E");
validationMap.put("rand", "sjrand");
Map<String, String> validationInfo = myKeepLineHttpUtil.sendPOST(validationURL, validationMap, "UTF-8");
System.out.println("------->>>>> captcha/captcha-check");
String stateCode = validationInfo.get("stateCode");
String backStr = validationInfo.get("result");
System.out.println(backStr);
if(stateCode.equals("200")){
json = new JSONObject(backStr);
System.out.println("json格式:" + json.toString());
}
if(json.getInt("result_code") != 4){
System.out.println("驗證碼輸入錯誤");
return "error";
}

Map<String, String> userInfoMap = new HashMap<>();
userInfoMap.put("username", userName);
userInfoMap.put("password", password);
userInfoMap.put("appid", "otn");
System.out.println(userInfoMap);
String userInfoURL = "https://kyfw.12306.cn/passport/web/login";
Map<String, String> userValidationInfo = myKeepLineHttpUtil.sendPOST(userInfoURL, userInfoMap, "UTF-8");
System.out.println("------->>>>> web/login");
stateCode = userValidationInfo.get("stateCode");
System.out.println(stateCode);
backStr =  userValidationInfo.get("result");
System.out.println(backStr);
if(stateCode.equals("200")){
json = new JSONObject(backStr);
System.out.println("json格式:" + json.toString());
}
if(json.getInt("result_code") != 0){
System.out.println("密碼輸入錯誤");
return "error";
}

json = chenkLoginState();
if(json.getInt("result_code") != 0){
System.out.println("登入確認出現錯誤");
return "error";
}

String uamauthclientURL = "https://kyfw.12306.cn/otn/uamauthclient";
Map<String, String> uamauthclientMap = new HashMap<String, String>();
uamauthclientMap.put("tk", json.getString("newapptk"));
Map<String, String> uamauthclientInfo = myKeepLineHttpUtil.sendPOST(uamauthclientURL, uamauthclientMap, "UTF-8");
stateCode = uamauthclientInfo.get("stateCode");
backStr = uamauthclientInfo.get("result");

if(stateCode.equals("200")){
json = new JSONObject(backStr);
System.out.println("json格式:" + json.toString());
}
if(json.getInt("result_code") != 0){
System.out.println("身份確認出現錯誤");
return "error";
}
resultUserName= json.getString("username");
return "success," + resultUserName;
}

/**
* 確認使用者登入狀態;
* @return
*/
public JSONObject chenkLoginState(){
JSONObject json = null;
String urlUamtk = "https://kyfw.12306.cn/passport/web/auth/uamtk";
Map<String, String> uamtkmap = new HashMap<>();
uamtkmap.put("appid", "otn");
System.out.println("------->>>>> auth/uamtk");
Map<String, String> sendPostUrlT = myKeepLineHttpUtil.sendPOST(urlUamtk, uamtkmap, "UTF-8");
String stateCode = sendPostUrlT.get("stateCode");
String backStr = sendPostUrlT.get("result");
System.out.println(stateCode);
System.out.println(backStr);
if(stateCode.equals("200")){
json = new JSONObject(backStr);
System.out.println(json);
}
return json;
}

/**
* 登入初始化動作;
* --主要是獲取cookies;
* @return
*/
public boolean loginInit(){
String urlInit = "https://kyfw.12306.cn/otn/login/init";
Map<String, String> sendGetT = myKeepLineHttpUtil.sendGET(urlInit, "UTF-8");
String stateCode = (String)sendGetT.get("stateCode");
System.out.println("------->>>>> login/init");
System.out.println(stateCode);
if(!stateCode.equals("200")){
return false;
}
return true;
}


/**
* 獲取驗證圖片;
* @return
*/
public boolean getValidationImg(){
String urlImg = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand";
Map<String, String> getStr = myKeepLineHttpUtil.sendGETByteStream(urlImg, "UTF-8");
if("200".equals(getStr.get("stateCode"))){
return true;
}
return false;
}

/**
* 獲取旅客資訊;
* @return
*/
public void setPassengerInfo(){
JSONArray array = null;
String urlPassengerInfo = "https://kyfw.12306.cn/otn/passengers/init";
Map<String, String> passengerInfoMap = new HashMap<>();
passengerInfoMap.put("_json_att", "");
Map<String, String> sendPOST = myKeepLineHttpUtil.sendPOST(urlPassengerInfo, passengerInfoMap, "UTF-8");
if("200".equals(sendPOST.get("stateCode"))){
String result = sendPOST.get("result");
int beginI = result.indexOf("passengers=");
int endI = result.indexOf("var pageSize");
String newStrI = result.substring(beginI, endI);
int beginII = newStrI.indexOf("[");
int endII = newStrI.indexOf("]");
newStrI = newStrI.substring(beginII,endII + 1);
array = new JSONArray(newStrI);
}

this.passengerInfo = array;
}


public boolean getTicketIn(String seadInfo, String passenger, String fromStationName, String toStationName, String goTrainDate){
printLog("開始刷票!");
boolean flag = false;
while(!flag){
flag = getTicket(seadInfo, passenger, fromStationName, toStationName, goTrainDate);
}
printLog("刷票成功");
System.out.println("成功!");
return flag;
}

/**
* 刷票;
* @return
*/
public boolean getTicket(String seadInfo, String passenger, String fromStationName, String toStationName, String goTrainDate){
printLog("找票");
Map<String, String> initialMap = new HashMap<>();
initialMap.put("seatInfo", seadInfo);
initialMap.put("goTrainDate", goTrainDate);
initialMap.put("backTrainDate", "");
initialMap.put("fromStationNameZh", fromStationName);
initialMap.put("toStationNameZh", toStationName);
initialMap.put("passenger", passenger);
List<Map<String, JSONObject>> list = new ArrayList<>();
boolean flag = true;
while (flag) {
list = separationTrainInfo(questTicket(initialMap), initialMap);
if(!list.isEmpty()){
printLog("找到可用的票了,可以提交訂單了");
System.out.println("找到了,可以提交單了");
flag = false;
}else{
printLog("未找到,繼續");
System.out.println("未找到,繼續");
}

}

boolean ticketIsHave = false;
printLog("開始嘗試提交訂單!");
for(int i = 0; i < list.size(); i++){
if(!ticketIsHave){
Map<String, JSONObject> tickets = list.get(i);
JSONObject ticket = tickets.get("jsonTrainInfo");
Map<String, String> ticketInfo = new HashMap<>();
try {
ticketInfo.put("secretStr", URLDecoder.decode(ticket.getString("0"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
ticketInfo.put("trainNo", ticket.getString("2"));
ticketInfo.put("stationTrainCode", ticket.getString("3"));
ticketInfo.put("fromStationName", ticket.getString("6"));
ticketInfo.put("toStationName", ticket.getString("7"));
ticketInfo.put("leftTicket", ticket.getString("12"));
ticketInfo.put("trainLocation", ticket.getString("15"));
//軟座
ticketInfo.put("23", ticket.getString("23"));
//無座
ticketInfo.put("26", ticket.getString("26"));
//硬臥
ticketInfo.put("28", ticket.getString("28"));
//硬座
ticketInfo.put("29", ticket.getString("29"));
//二等座
ticketInfo.put("30", ticket.getString("30"));
//一等座
ticketInfo.put("31", ticket.getString("31"));
//商務特等座
ticketInfo.put("32", ticket.getString("32"));
JSONObject seat = tickets.get("jsonSeatInfo");
StringBuffer usableSeat = new StringBuffer();
Iterator<String> keys = seat.keys();
while (keys.hasNext()) {
String key = keys.next();
//ticketInfo.get(seat.getString(key))
usableSeat.append(key + ",");
}
usableSeat.deleteCharAt(usableSeat.length() - 1);
ticketInfo.put("usableSeat", usableSeat.toString());
ticketInfo.putAll(initialMap);
ticketIsHave = orderRequest(ticketInfo);
}
}
if(ticketIsHave){
return true;
}
return false;
}

/**
* 查票;
* @param info
* @return
*/
public JSONArray questTicket(Map<String,String> info){

//List<String> seatList = Arrays.asList(seatArray);
List<Map<String, JSONObject>> result = new ArrayList<Map<String, JSONObject>>();
JSONArray jsonResult = null;
JSONObject json = null;
StringBuffer questTicketURL = new StringBuffer();
questTicketURL.append("https://kyfw.12306.cn/otn/leftTicket/queryZ?")
.append("leftTicketDTO.train_date=" + info.get("goTrainDate"))
.append(info.get("backTrainDate") == "" ? "":info.get("backTrainDate"))
.append("&leftTicketDTO.from_station=" + stationName.getString(info.get("fromStationNameZh")))
.append("&leftTicketDTO.to_station=" + stationName.getString(info.get("toStationNameZh")))
.append("&purpose_codes=ADULT");

Map<String, String> sendGET = myKeepLineHttpUtil.sendGET(questTicketURL.toString(), "UTF-8");
String stateCode = sendGET.get("stateCode");
String backStr = sendGET.get("result");
if(stateCode.equals("200")){
try {
json = new JSONObject(backStr);
JSONObject jsonData = json.getJSONObject("data");
if (jsonData.getString("flag").equals("1")) {

jsonResult = jsonData.getJSONArray("result");

}
} catch (JSONException e) {
e.printStackTrace();
return jsonResult;
}
}

printLog("查詢了車票!");
return jsonResult;
}

/**
* 將查詢的車次進行分離;
* @param trainInfo
* @param info
* @return
*/
public List<Map<String, JSONObject>> separationTrainInfo(JSONArray trainInfo, Map<String,String> info){
List<Map<String, JSONObject>> result = new ArrayList<Map<String, JSONObject>>();
String[] seatArray = info.get("seatInfo").split(",");
for (int i = 0; i < trainInfo.length(); i++) {
Map<String, JSONObject> map = new HashMap<>();
String trainInfos = trainInfo.getString(i);
String[] split = trainInfos.split("\\|");
JSONObject jsonTrainInfo = new JSONObject();
JSONObject jsonSeatInfo = new JSONObject();
int index = 0;
for (int j = 0; j < seatArray.length; j++) {

String str = split[Integer.parseInt(seatArray[j])];
if (!"".equals(str) & !"無".equals(str)) {
jsonSeatInfo.put(seatArray[j], "OK");
index++;
}
}
if (index > 0) {
for (int k = 0; k < split.length; k++) {
jsonTrainInfo.put(k + "", split[k]);
}
}
if (jsonTrainInfo.length() > 0) {
map.put("jsonTrainInfo", jsonTrainInfo);
}
if (jsonSeatInfo.length() > 0) {
map.put("jsonSeatInfo", jsonSeatInfo);
}
if (!map.isEmpty()) {
result.add(map);
}
}
return result;
}

JSONArray oldPassengersArray = new JSONArray();
public boolean orderRequest(Map<String, String> map){
printLog("開始提交請求訂單!");
JSONObject json = null;
String submitOrderRequestURL = "https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest";
Map<String, String> submitOrderMap = new HashMap<>();
submitOrderMap.put("secretStr", map.get("secretStr"));
submitOrderMap.put("query_from_station_name", map.get("fromStationNameZh") == "" ? "" : map.get("fromStationNameZh"));
submitOrderMap.put("query_to_station_name", map.get("toStationNameZh") == "" ? "" : map.get("toStationNameZh"));
submitOrderMap.put("train_date", map.get("goTrainDate") == ""? "" : map.get("goTrainDate"));
submitOrderMap.put("back_train_date", map.get("backTrainDate") == ""? map.get("goTrainDate") : map.get("backTrainDate"));
submitOrderMap.put("tour_flag", "dc");
submitOrderMap.put("purpose_codes","ADULT");
submitOrderMap.put("undefined", "");
Map<String, String> submitOrderInfo = myKeepLineHttpUtil.sendPOST(submitOrderRequestURL, submitOrderMap, "UTF-8");
if(submitOrderInfo.get("stateCode").equals("200")){
json = new JSONObject(submitOrderInfo.get("result"));
System.out.println(json.toString());
json.getBoolean("status");
if(!json.getBoolean("status")){
System.out.println("請求訂單失敗!");
printLog("請求訂單失敗!");
return false;
}
}else{
System.out.println("請求訂單失敗!");
printLog("請求訂單失敗!");
return false;
}

printLog("開始獲取initDC檔案!");
String initDcURL = "https://kyfw.12306.cn/otn/confirmPassenger/initDc";
String repeatSubmitToken = "";
String key_check_isChange = "";
Map<String, String> initDcMap = new HashMap<>();
initDcMap.put("_json_att", "");
Map<String, String> initDcInfo = myKeepLineHttpUtil.sendPOST(initDcURL, initDcMap, "UTF-8");
if(initDcInfo.get("stateCode").equals("200")){
String result = initDcInfo.get("result");
Pattern pattern = Pattern.compile("globalRepeatSubmitToken\\s=\\s\'\\w{32}\'");
//'key_check_isChange':'8A76641C1E316E76813A89EB75492F56320FDCFF5FC54D6994B4DE5E',
Matcher matcher = pattern.matcher(result);
if(matcher.find()){  
   for(int i=0; i<=matcher.groupCount(); i++){  
   repeatSubmitToken += matcher.group(i);  
   }  
}
int beginIndex = repeatSubmitToken.indexOf("'");
repeatSubmitToken = repeatSubmitToken.substring(beginIndex + 1, beginIndex + 33);
pattern = Pattern.compile("\'key_check_isChange\':\'\\w{56}\'");
Matcher matcher2 = pattern.matcher(result);
if(matcher2.find()){  
   for(int i=0; i<=matcher2.groupCount(); i++){  
   key_check_isChange += matcher2.group(i);  
   }  
}
key_check_isChange = key_check_isChange.split(":")[1];
key_check_isChange = key_check_isChange.substring(1, key_check_isChange.length() - 1);
}else{
printLog("獲取repeatSubmitToken失敗!");
System.out.println("獲取repeatSubmitToken失敗!");
return false;
}

/**
* 這裡可能會出現問題,不知道是不是一定要獲取這個資訊,還是可以用後之前獲取的資訊;
*/
printLog("開始獲取旅客資訊!");
if(oldPassengersArray.length() < 1){
String passengerDTOsURL = "https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs";
Map<String, String> passengerMap = new HashMap<>();
passengerMap.put("_json_att", "");
passengerMap.put("REPEAT_SUBMIT_TOKEN", repeatSubmitToken);
Map<String, String> passengerinfo = myKeepLineHttpUtil.sendPOST(passengerDTOsURL, passengerMap, "UTF-8");
if(passengerinfo.get("stateCode").equals("200")){
String backStr = passengerinfo.get("result");
json = new JSONObject(backStr);
System.out.println(json.toString());
oldPassengersArray = json.getJSONObject("data").getJSONArray("normal_passengers");
}else{
printLog("獲取旅客資訊失敗!");
System.out.println("獲取旅客資訊失敗!");
return false;
}
}

JSONArray newPassengersArray = new JSONArray();
printLog("開始拼裝旅客資訊!");
String passenger = map.get("passenger");
String[] passengersStr = passenger.split(",");
for(int i = 0; i < passengersStr.length; i++){
for(int j = 0; j < oldPassengersArray.length(); j++){
JSONObject passengerJson = oldPassengersArray.getJSONObject(j);
if(passengerJson.getString("passenger_name").equals(passengersStr[i])){
newPassengersArray.put(newPassengersArray.length(), passengerJson);
break;
}
}
}

String[] usableSeat = map.get("usableSeat").split(",");
printLog("開始檢查訂單資訊!");
String checkOrderInfoURL = "https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo";
String queueCountURL =  "https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount";
String confirmSingleForQueueURL = "https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue";
for(int i = 0; i <usableSeat.length; i++){
Map<String, String> checkOrderInfoMap = new HashMap<>();
checkOrderInfoMap.put("cancel_flag", "2");
checkOrderInfoMap.put("bed_level_order_num", "000000000000000000000000000000");

StringBuffer passengerTicketStr = new StringBuffer();
StringBuffer oldPassengerStr = new StringBuffer();
for(int j = 0; j < newPassengersArray.length(); j++){
JSONObject passengerJson = newPassengersArray.getJSONObject(j);
passengerTicketStr.append(parseSeat(usableSeat[i])).append(",0").append("," + passengerJson.getString("passenger_type")).append("," + passengerJson.getString("passenger_name"))
.append("," + passengerJson.getString("passenger_id_type_code")).append("," + passengerJson.getString("passenger_id_no")).append("," + passengerJson.getString("mobile_no"))
.append(",N").append("_");
oldPassengerStr.append(passengerJson.getString("passenger_name")).append("," + passengerJson.getString("passenger_id_type_code")).append("," + passengerJson.getString("passenger_id_no"))
.append("," + passengerJson.getString("passenger_type")).append("_");
}
passengerTicketStr.deleteCharAt(passengerTicketStr.length() - 1);
//oldPassengerStr.deleteCharAt(oldPassengerStr.length() - 1);
checkOrderInfoMap.put("passengerTicketStr", passengerTicketStr.toString());
checkOrderInfoMap.put("oldPassengerStr", oldPassengerStr.toString());
checkOrderInfoMap.put("tour_flag", "dc");
checkOrderInfoMap.put("randCode", "");
checkOrderInfoMap.put("whatsSelect", "1");
checkOrderInfoMap.put("_json_att", "");
checkOrderInfoMap.put("REPEAT_SUBMIT_TOKEN", repeatSubmitToken);
Map<String, String> checkOrderInfo = myKeepLineHttpUtil.sendPOST(checkOrderInfoURL, checkOrderInfoMap, "UTF-8");
if(checkOrderInfo.get("stateCode").equals("200")){
json = new JSONObject(checkOrderInfo.get("result"));
if(!json.getBoolean("status")){
System.out.println("checkOrderInfo 請求失敗!");
printLog("checkOrderInfo 請求失敗!");
return false;
}
}else{
System.out.println("checkOrderInfo 請求失敗!");
printLog("checkOrderInfo 請求失敗!");
return false;
}

printLog("開始獲取queueCount!");
Map<String, String> queueCountMap = new HashMap<>();
queueCountMap.put("train_date", MyDateUtil.getLongTypeDate(map.get("goTrainDate")) + " (中國標準時間)");
queueCountMap.put("train_no", map.get("trainNo"));
queueCountMap.put("stationTrainCode", "stationTrainCode");
queueCountMap.put("seatType", map.get(usableSeat[i]));
queueCountMap.put("fromStationTelecode", map.get("fromStationName"));
queueCountMap.put("toStationTelecode", map.get("toStationName"));
queueCountMap.put("leftTicket", map.get("leftTicket"));
queueCountMap.put("purpose_codes", "00");
queueCountMap.put("train_location", map.get("trainLocation"));
queueCountMap.put("_json_att", "");
queueCountMap.put("REPEAT_SUBMIT_TOKEN", repeatSubmitToken);
Map<String, String> queueCountInfo = myKeepLineHttpUtil.sendPOST(queueCountURL, queueCountMap, "UTF-8");
if(queueCountInfo.get("stateCode").equals("200")){
String backStr = queueCountInfo.get("result");
json = new JSONObject(backStr);
if(!json.getBoolean("status")){
printLog("queueCount 請求失敗!");
System.out.println("queueCount 請求失敗!");
return false;
}
}else{
printLog("queueCount 請求失敗!");
System.out.println("queueCount 請求失敗!");
return false;
}

printLog("confirmSingleForQueue 請求開始!");
Map<String, String> confirmSingleForQueueMap = new HashMap<>();
confirmSingleForQueueMap.put("passengerTicketStr", passengerTicketStr.toString());
confirmSingleForQueueMap.put("oldPassengerStr", oldPassengerStr.toString());
confirmSingleForQueueMap.put("randCode", "");
confirmSingleForQueueMap.put("purpose_codes", "00" );
confirmSingleForQueueMap.put("key_check_isChange", key_check_isChange);
confirmSingleForQueueMap.put("leftTicketStr", map.get("leftTicket"));
confirmSingleForQueueMap.put("train_location", map.get("trainLocation"));
confirmSingleForQueueMap.put("choose_seats", "");
confirmSingleForQueueMap.put("seatDetailType", "000");
confirmSingleForQueueMap.put("whatsSelect", "1");
confirmSingleForQueueMap.put("roomType", "00");
confirmSingleForQueueMap.put("dwAll", "N");
confirmSingleForQueueMap.put("_json_att", "");
confirmSingleForQueueMap.put("REPEAT_SUBMIT_TOKEN", repeatSubmitToken);
Map<String, String> confirmSingleForQueueInfo = myKeepLineHttpUtil.sendPOST(confirmSingleForQueueURL, confirmSingleForQueueMap, "UTF-8");
if(confirmSingleForQueueInfo.get("stateCode").equals("200")){
String backStr = confirmSingleForQueueInfo.get("result");
json = new JSONObject(backStr);
if(!json.getJSONObject("data").getBoolean("submitStatus")){
System.out.println("confirmSingleForQueue 請求失敗!");
printLog("confirmSingleForQueue 請求失敗!");
return false;
}
}else{
System.out.println("confirmSingleForQueue 請求失敗!");
printLog("confirmSingleForQueue 請求失敗!");
return false;
}


String orderSequenceNo = queryOrderWaitTime(repeatSubmitToken);
if("success".equals(orderSequenceNo)){
System.out.println("購買成功,在規定的時間支付!");
printLog("購買成功,在規定的時間支付!");
return true;
}else{
String resultOrderForDcQueueURL = "https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue";
Map<String, String> resultOrderForDcQueueMap = new HashMap<>();
resultOrderForDcQueueMap.put("orderSequence_no", orderSequenceNo);
resultOrderForDcQueueMap.put("_json_att", "");
resultOrderForDcQueueMap.put("REPEAT_SUBMIT_TOKEN", repeatSubmitToken);
Map<String, String> resultOrderForDcQueueInfo = myKeepLineHttpUtil.sendPOST(resultOrderForDcQueueURL, resultOrderForDcQueueMap, "UTF-8");
if(resultOrderForDcQueueInfo.get("stateCode").equals("200")){
String backStr = resultOrderForDcQueueInfo.get("result");
json = new JSONObject(backStr);
if(json.getJSONObject("data").getString("submitStatus").equals("True")){
System.out.println("購買成功,在規定的時間支付!");
printLog("購買成功,在規定的時間支付!");
return true;
}
}else{
System.out.println("購買失敗!");
printLog("購買失敗!");
return false;
}
}
}
return false;
}

public String queryOrderWaitTime(String RST){
printLog("queryOrderWaitTime 開始!");
StringBuffer queryOrderWaitTime = new StringBuffer();
String resultStr = null;
JSONObject json = null;
queryOrderWaitTime.append("https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime").append("?")
.append("random=" + System.currentTimeMillis()).append("&_json_att=")
.append("&REPEAT_SUBMIT_TOKEN=" + RST);

Map<String, String> queryOrderWaitTimeInfo = myKeepLineHttpUtil.sendGET(queryOrderWaitTime.toString(), "UTF-8");
if(queryOrderWaitTimeInfo.get("stateCode").equals("200")){
String backStr = queryOrderWaitTimeInfo.get("result");
json = new JSONObject(backStr);
int waitTime = json.getJSONObject("data").getInt("waitTime");
if(waitTime == -4){
return "success";
}else{
resultStr = json.getJSONObject("data").getString("orderId");
if(resultStr.equals("") | resultStr == null){
resultStr = queryOrderWaitTime(RST);
}
}
}
return resultStr;
}

public static void main(String[] args) {

}

public Code(){
setStationName();
}

public JTextPane getLogInfo() {
return logInfo;
}


public void setLogInfo(JTextPane logInfo) {
this.logInfo = logInfo;
}


/**
* 列印日誌;
* @param massage
*/
public void printLog(String massage){
if(this.logInfo == null){
return;
}
this.logInfo.setText(this.logInfo.getText() + massage + "\n");
this.logInfo.setSelectionStart(this.logInfo.getText().length());
this.logInfo.updateUI();
}

public String parseSeat(String number){
String result = null;
switch(number){
case "26":
result = "1";
break;
case "29":
result = "1";
break;
case "28":
result = "3";
break;
case "23":
result = "4";
break;
case "31":
result = "M";
break;
case "30":
result = "O";
break;
case "32":
result = "9";
break;
}
return result;
}
}

 登入的介面:

package com.text.view;


import java.awt.EventQueue;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;


import com.text.cores.Code;
import com.text.utils.MyKeepLineHttpUtil;


import javax.swing.JLabel;
import javax.swing.JOptionPane;


import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;


import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;


public class LoginView extends JFrame {


/**

*/
private static final long serialVersionUID = 1L;


private JPanel contentPane;
private JTextField userNameText;
private JPasswordField passwordText;

private StringBuffer validatinCodeStr = new StringBuffer();
private boolean validationImgInit;


Code code = new Code();

private void addValidatinCodeStr(String str){
this.validatinCodeStr.append(str);

}
private void closeValidatinCodeStr(){
this.validatinCodeStr = this.validatinCodeStr.delete(0, validatinCodeStr.length());
}


/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginView frame = new LoginView();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


/**
* Create the frame.
*/
public LoginView() {
setTitle("啦啦啦啦,德瑪西亞");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 595, 563);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("12306登入");
lblNewLabel.setFont(new Font("宋體", Font.BOLD, 18));
lblNewLabel.setToolTipText("");
lblNewLabel.setBounds(254, 41, 97, 49);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("使用者名稱:");
lblNewLabel_1.setBounds(165, 119, 54, 15);
contentPane.add(lblNewLabel_1);

userNameText = new JTextField();
userNameText.setBounds(254, 116, 141, 21);
contentPane.add(userNameText);
userNameText.setColumns(10);

JLabel lblNewLabel_3 = new JLabel("密碼:");
lblNewLabel_3.setBounds(165, 171, 54, 15);
contentPane.add(lblNewLabel_3);

passwordText = new JPasswordField();
passwordText.setBounds(254, 168, 141, 21);
contentPane.add(passwordText);

JLabel lblNewLabel_2 = new JLabel();

JButton jb_login = new JButton("登入");
jb_login.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
String username =userNameText.getText();
String password = new String(passwordText.getPassword());
if(!"".equals(username) && !"".equals(password) && validationImgInit == true){
String login = code.login(username, password, validatinCodeStr.toString());
String[] split = login.split(",");
if("success".equals(split[0])){
TicketView frame = new TicketView(split[1], code);
frame.setVisible(true);
LoginView.this.dispose();
}else{
JOptionPane.showMessageDialog(null, "登入失敗!", "溫馨提示", JOptionPane.QUESTION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "不能登入,請檢查必填資訊!", "溫馨提示", JOptionPane.QUESTION_MESSAGE);
}
}
});

jb_login.setBounds(165, 455, 93, 23);
contentPane.add(jb_login);

JButton jb_reset = new JButton("重置");
jb_reset.setBounds(292, 455, 93, 23);
contentPane.add(jb_reset);

JButton jb_flush = new JButton("重新整理驗證碼");
jb_flush.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
getValidationImg();
setValidationCode(lblNewLabel_2);
//lblNewLabel_2.setIcon(null);
closeValidatinCodeStr();
LoginView.this.contentPane.revalidate();
}
});
jb_flush.setBounds(224, 215, 93, 23);
contentPane.add(jb_flush);

lblNewLabel_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
/**
* 1是左鍵;
* 2是滾輪;
* 3是右鍵;
*/
int button = e.getButton();
if(1 == button){
int xI = e.getX();
int yI = e.getY();
setFlag(lblNewLabel_2, xI, yI);
String str = xI + "," + yI + ",";
addValidatinCodeStr(str);
}
//JOptionPane.showMessageDialog(null, "QUESTION_MESSAGE", "QUESTION_MESSAGE", JOptionPane.QUESTION_MESSAGE);
}
});
getValidationImg();
setValidationCode(lblNewLabel_2);
lblNewLabel_2.setBackground(Color.GRAY);
lblNewLabel_2.setBounds(165, 248, 293, 190);
contentPane.add(lblNewLabel_2);


}

private boolean getValidationImg(){
validationImgInit = code.getValidationImg();
return validationImgInit;
}


/**
* 設定驗證圖片;
* @param jlabel
*/
private void setValidationCode(JLabel jlabel){
jlabel.removeAll();
//String str = LoginView.class.getClassLoader().getResource("").getPath() + "resource/123.jpg";
//String url = str.substring(1, str.length()); 
//Icon icon = new ImageIcon(url);
String filePath = getFilePath();
System.out.println(filePath);

URL resource = LoginView.class.getClassLoader().getResource("resource/123.jpg");
Image img = Toolkit.getDefaultToolkit().createImage(filePath); 

jlabel.setIcon(new ImageIcon(img));
jlabel.repaint();
jlabel.updateUI();
jlabel.setVisible(false);
jlabel.setVisible(true);
}

/**
* 設定驗證碼標記;
* @param jlabel
* @param x
* @param y
*/
private void setFlag(JLabel jlabel, int x, int y){
URL str = LoginView.class.getClassLoader().getResource("resource/flag1.jpg");
//String url = str.substring(1, str.length()); 
Icon icon = new ImageIcon(str);
JLabel flagImg = new JLabel(icon);
flagImg.setBounds(x, y, 26, 24);
jlabel.add(flagImg);
jlabel.repaint();
}

public static String getJarPath()  
    {  
        File file = getFile();  
        if (file == null)  
            return null;  
        return file.getAbsolutePath();  
    } 
    
    private static File getFile()  
    {  
        // 關鍵是這行...  
        String path = LoginView.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
        try  
        {  
            path = java.net.URLDecoder.decode(path, "UTF-8"); // 轉換處理中文及空格  
        }  
        catch (java.io.UnsupportedEncodingException e)  
        {  
            return null;  
        }  
        return new File(path);  
    }
    
    public String getFilePath(){
    String jarPath = getJarPath();
    int lastIndexOf = jarPath.lastIndexOf("\\");
    jarPath = jarPath.substring(0, lastIndexOf);
    return jarPath + "\\imgTemp\\123.jpg";
    }
}

刷票的介面:

package com.text.view;


import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.EventQueue;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


import java.awt.Font;


import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JTextField;
import javax.swing.JRadioButton;


import java.awt.Color;


import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextPane;


import org.json.JSONArray;
import org.json.JSONObject;


import com.text.Entity.TrainInfo;
import com.text.cores.Code;
import com.text.utils.MyUtil;


import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;


import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JScrollPane;


public class TicketView extends JFrame {


/**

*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField goTrainDate;
private JTextField backTrainDate;
private JTextPane logInfo;

private Code code;
private JTextField fromStationName;
private JTextField toStationName;



public Code getCode() {
return code;
}


public void setCode(Code code) {
this.code = code;
}


/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TicketView frame = new TicketView();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


/**
* Create the frame.
*/
public TicketView() {
setTitle("我QQ:2677688850, 啦啦啦啦~");
initCode();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 851, 797);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
String user = "張三";
JLabel showUser = new JLabel("歡迎登陸:" + user);
showUser.setFont(new Font("宋體", Font.BOLD, 18));
showUser.setBounds(38, 10, 190, 39);
contentPane.add(showUser);

JLabel label = new JLabel("出發時間:");
label.setBounds(38, 168, 69, 15);
contentPane.add(label);

goTrainDate = new JTextField();
goTrainDate.setBounds(117, 165, 126, 21);
contentPane.add(goTrainDate);
goTrainDate.setColumns(10);

JLabel label_1 = new JLabel("--");
label_1.setBounds(253, 168, 23, 15);
contentPane.add(label_1);

JLabel label_2 = new JLabel("返程時間:");
label_2.setBounds(286, 168, 67, 15);
contentPane.add(label_2);

backTrainDate = new JTextField();
backTrainDate.setColumns(10);
backTrainDate.setBounds(363, 165, 126, 21);
contentPane.add(backTrainDate);

JRadioButton rdbtnNewRadioButton = new JRadioButton("單程");
rdbtnNewRadioButton.setSelected(true);
rdbtnNewRadioButton.setBounds(520, 164, 61, 23);
contentPane.add(rdbtnNewRadioButton);

JRadioButton radioButton = new JRadioButton("往返");
radioButton.setBounds(596, 164, 61, 23);
contentPane.add(radioButton);

JPanel passengerList = new JPanel();
passengerList.setToolTipText("");
passengerList.setBounds(38, 232, 750, 69);
addPassengerInfo(passengerList);
contentPane.add(passengerList);
passengerList.setLayout(null);

JLabel label_3 = new JLabel("選擇要購票的人");
label_3.setBackground(Color.GREEN);
label_3.setBounds(38, 207, 93, 15);
contentPane.add(label_3);

logInfo = new JTextPane();
code.setLogInfo(logInfo);
logInfo.setBounds(38, 619, 750, 130);
//logInfo.setCaretPosition(logInfo.getStyledDocument().getLength()); 
JScrollPane jp = new JScrollPane(logInfo);
jp.setBounds(38, 619, 750, 130);
contentPane.add(jp);

JLabel label_4 = new JLabel("出發站:");
label_4.setBounds(38, 129, 54, 15);
contentPane.add(label_4);

JLabel lblNewLabel = new JLabel("目的站:");
lblNewLabel.setBounds(285, 129, 54, 15);
contentPane.add(lblNewLabel);

fromStationName = new JTextField();
fromStationName.setBounds(116, 126, 126, 21);
contentPane.add(fromStationName);
fromStationName.setColumns(10);

JLabel label_5 = new JLabel("--");
label_5.setBounds(252, 129, 23, 15);
contentPane.add(label_5);

toStationName = new JTextField();
toStationName.setColumns(10);
toStationName.setBounds(362, 126, 126, 21);
contentPane.add(toStationName);

JLabel label_6 = new JLabel("系統日誌");
label_6.setBounds(38, 594, 54, 15);
contentPane.add(label_6);

JPanel seatList = new JPanel();
seatList.setBounds(38, 46, 512, 44);
contentPane.add(seatList);
seatList.setLayout(null);

JCheckBox chckbxNewCheckBox = new JCheckBox("一等座");
chckbxNewCheckBox.setBounds(6, 6, 70, 23);
seatList.add(chckbxNewCheckBox);

JCheckBox checkBox = new JCheckBox("二等座");
checkBox.setBounds(89, 6, 76, 23);
seatList.add(checkBox);

JCheckBox checkBox_1 = new JCheckBox("軟臥");
checkBox_1.setBounds(181, 6, 61, 23);
seatList.add(checkBox_1);

JCheckBox checkBox_2 = new JCheckBox("硬臥");
checkBox_2.setBounds(268, 6, 61, 23);
seatList.add(checkBox_2);

JCheckBox checkBox_3 = new JCheckBox("硬座");
checkBox_3.setBounds(353, 6, 61, 23);
seatList.add(checkBox_3);

JCheckBox checkBox_4 = new JCheckBox("無座");
checkBox_4.setBounds(444, 6, 61, 23);
seatList.add(checkBox_4);

JLabel lblNewLabel_1 = new JLabel("車次資訊");
lblNewLabel_1.setBounds(38, 331, 54, 15);
contentPane.add(lblNewLabel_1);

HeroTableModel model = new HeroTableModel();
        JTable table = new JTable(model);

JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(38, 356, 750, 231);
contentPane.add(scrollPane);

JButton jb_questTicket = new JButton("查票");
jb_questTicket.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String fromStationName = TicketView.this.fromStationName.getText();
String toStationName = TicketView.this.toStationName.getText();
String goTrainDate = TicketView.this.goTrainDate.getText();
if("".equals(fromStationName) & "".equals(toStationName) & "".equals(goTrainDate)){
JOptionPane.showMessageDialog(null, "檢查必填欄位", "溫馨提示", JOptionPane.PLAIN_MESSAGE);
return;
}
Map<String, String> initialMap = new HashMap<>();
initialMap.put("goTrainDate", goTrainDate);
initialMap.put("backTrainDate", "");
initialMap.put("fromStationNameZh", fromStationName);
initialMap.put("toStationNameZh", toStationName);
JSONArray trainInfos = code.questTicket(initialMap);
HeroTableModel myModel = (HeroTableModel) table.getModel();
myModel.clearData();
for(int i = 0; i < trainInfos.length(); i++){
String trainInfo = trainInfos.getString(i);
String[] trainInfoArray = trainInfo.split("\\|");
String trainNo = trainInfoArray[3];
String formTime = trainInfoArray[8];
String arrivalTime = trainInfoArray[9];
String s23 = trainInfoArray[23];
String s26 = trainInfoArray[26];
String s28 = trainInfoArray[28];
String s29 = trainInfoArray[29];
String s30 = trainInfoArray[30];
String s31 = trainInfoArray[31];
String s32 = trainInfoArray[32];
TrainInfo info = new TrainInfo(trainNo, formTime, arrivalTime, s23, s26, s28, s29, s30, s31, s32);
myModel.addData(info);
}
table.updateUI();
}
});
jb_questTicket.setBounds(695, 41, 93, 23);
contentPane.add(jb_questTicket);

JButton jb_vieforTicket = new JButton("刷票");
jb_vieforTicket.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
StringBuffer seatNumber = new StringBuffer();
Component[] seats = seatList.getComponents();
for(int i = 0; i < seatList.getComponentCount(); i++){
if(seats[i] instanceof JCheckBox){
JCheckBox is = (JCheckBox) seats[i];
if(is.isSelected()){
seatNumber.append(judgeSead(is.getText()) + ",");
}
}
}

StringBuffer passengerName = new StringBuffer();
Component[] passengers = passengerList.getComponents();
for(int j = 0; j < passengers.length; j++){
if(passengers[j] instanceof JCheckBox){
JCheckBox is = (JCheckBox) passengers[j];
passengerName.append(is.getText());
}
}

String fromStationName = TicketView.this.fromStationName.getText();
String toStationName = TicketView.this.toStationName.getText();
String goTrainDate = TicketView.this.goTrainDate.getText();
String seatNumberStr = seatNumber.deleteCharAt(seatNumber.length() - 1).toString();
String passengerNameStr = passengerName.deleteCharAt(passengerName.length() - 1).toString();
if(fromStationName == null & toStationName == null & goTrainDate == null & seatNumberStr == null & passengerNameStr == null){
return;
}
code.getTicketIn(seatNumberStr, passengerNameStr, fromStationName, toStationName, goTrainDate);
}
});
jb_vieforTicket.setBounds(695, 92, 93, 23);
contentPane.add(jb_vieforTicket);



}

/**
* 新增旅客資訊;
* @param panel
*/
public void addPassengerInfo(JPanel panel){
JSONArray passengerInfo = code.getPassengerInfo();
if(passengerInfo != null){
int x = 0;
int y = 0;
for(int i = 0; i < passengerInfo.length(); i++){
String passengerName = passengerInfo.getJSONObject(i).getString("passenger_name");
if(i != 0 && i % 6 == 0){
x = 0;
y = y + 30;
}
JCheckBox Passenger = new JCheckBox(passengerName);
Passenger.setBounds(x, y, 76, 23);
panel.add(Passenger);
x = x + 100;
}
}
}

/**
* 判斷座位;
*/
public String judgeSead(String text){
String result = "";
switch(text){
case "軟座":
result = "23";
break;
case "無座":
result = "26";
break;
case "硬臥":
result = "28";
break;
case "硬座":
result = "29";
break;
case "二等座":
result = "30";
break;
case "一等座":
result = "31";
break;
case "特等座":
result = "32";
break;
}
return result;
}

public TicketView(String user, Code code){
setCode(code);
initCode();
setTitle("我QQ:2677688850, 啦啦啦啦~");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 851, 797);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//String user = "張三";
JLabel showUser = new JLabel("歡迎登陸:" + user);
showUser.setFont(new Font("宋體", Font.BOLD, 18));
showUser.setBounds(38, 10, 190, 39);
contentPane.add(showUser);

JLabel label = new JLabel("出發時間:");
label.setBounds(38, 168, 69, 15);
contentPane.add(label);

goTrainDate = new JTextField();
goTrainDate.setBounds(117, 165, 126, 21);
contentPane.add(goTrainDate);
goTrainDate.setColumns(10);

JLabel label_1 = new JLabel("--");
label_1.setBounds(253, 168, 23, 15);
contentPane.add(label_1);

JLabel label_2 = new JLabel("返程時間:");
label_2.setBounds(286, 168, 67, 15);
contentPane.add(label_2);

backTrainDate = new JTextField();
backTrainDate.setColumns(10);
backTrainDate.setBounds(363, 165, 126, 21);
contentPane.add(backTrainDate);

JRadioButton rdbtnNewRadioButton = new JRadioButton("單程");
rdbtnNewRadioButton.setSelected(true);
rdbtnNewRadioButton.setBounds(520, 164, 61, 23);
contentPane.add(rdbtnNewRadioButton);

JRadioButton radioButton = new JRadioButton("往返");
radioButton.setBounds(596, 164, 61, 23);
contentPane.add(radioButton);

JPanel passengerList = new JPanel();
passengerList.setToolTipText("");
passengerList.setBounds(38, 232, 750, 69);
addPassengerInfo(passengerList);
contentPane.add(passengerList);
passengerList.setLayout(null);

JLabel label_3 = new JLabel("選擇要購票的人");
label_3.setBackground(Color.GREEN);
label_3.setBounds(38, 207, 93, 15);
contentPane.add(label_3);

logInfo = new JTextPane();
code.setLogInfo(logInfo);
logInfo.setBounds(38, 619, 750, 130);
 
JScrollPane jp = new JScrollPane(logInfo);
jp.setBounds(38, 619, 750, 130);
contentPane.add(jp);

JLabel label_4 = new JLabel("出發站:");
label_4.setBounds(38, 129, 54, 15);
contentPane.add(label_4);

JLabel lblNewLabel = new JLabel("目的站:");
lblNewLabel.setBounds(285, 129, 54, 15);
contentPane.add(lblNewLabel);

fromStationName = new JTextField();
fromStationName.setBounds(116, 126, 126, 21);
contentPane.add(fromStationName);
fromStationName.setColumns(10);

JLabel label_5 = new JLabel("--");
label_5.setBounds(252, 129, 23, 15);
contentPane.add(label_5);

toStationName = new JTextField();
toStationName.setColumns(10);
toStationName.setBounds(362, 126, 126, 21);
contentPane.add(toStationName);

JLabel label_6 = new JLabel("系統日誌");
label_6.setBounds(38, 594, 54, 15);
contentPane.add(label_6);

JPanel seatList = new JPanel();
seatList.setBounds(38, 46, 512, 44);
contentPane.add(seatList);
seatList.setLayout(null);

JCheckBox chckbxNewCheckBox = new JCheckBox("一等座");
chckbxNewCheckBox.setBounds(6, 6, 70, 23);
seatList.add(chckbxNewCheckBox);

JCheckBox checkBox = new JCheckBox("二等座");
checkBox.setBounds(89, 6, 76, 23);
seatList.add(checkBox);

JCheckBox checkBox_1 = new JCheckBox("軟臥");
checkBox_1.setBounds(181, 6, 61, 23);
seatList.add(checkBox_1);

JCheckBox checkBox_2 = new JCheckBox("硬臥");
checkBox_2.setBounds(268, 6, 61, 23);
seatList.add(checkBox_2);

JCheckBox checkBox_3 = new JCheckBox("硬座");
checkBox_3.setBounds(353, 6, 61, 23);
seatList.add(checkBox_3);

JCheckBox checkBox_4 = new JCheckBox("無座");
checkBox_4.setBounds(444, 6, 61, 23);
seatList.add(checkBox_4);

JLabel lblNewLabel_1 = new JLabel("車次資訊");
lblNewLabel_1.setBounds(38, 331, 54, 15);
contentPane.add(lblNewLabel_1);

HeroTableModel model = new HeroTableModel();
        JTable table = new JTable(model);

JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(38, 356, 750, 231);
contentPane.add(scrollPane);

JButton jb_questTicket = new JButton("查票");
jb_questTicket.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String fromStationName = TicketView.this.fromStationName.getText();
String toStationName = TicketView.this.toStationName.getText();
String goTrainDate = TicketView.this.goTrainDate.getText();
if("".equals(fromStationName) & "".equals(toStationName) & "".equals(goTrainDate)){
JOptionPane.showMessageDialog(null, "檢查必填欄位", "溫馨提示", JOptionPane.PLAIN_MESSAGE);
return;
}
Map<String, String> initialMap = new HashMap<>();
initialMap.put("goTrainDate", goTrainDate);
initialMap.put("backTrainDate", "");
initialMap.put("fromStationNameZh", fromStationName);
initialMap.put("toStationNameZh", toStationName);
JSONArray trainInfos = code.questTicket(initialMap);
HeroTableModel myModel = (HeroTableModel) table.getModel();
myModel.clearData();
for(int i = 0; i < trainInfos.length(); i++){
String trainInfo = trainInfos.getString(i);
String[] trainInfoArray = trainInfo.split("\\|");
String trainNo = trainInfoArray[3];
String formTime = trainInfoArray[8];
String arrivalTime = trainInfoArray[9];
String s23 = trainInfoArray[23];
String s26 = trainInfoArray[26];
String s28 = trainInfoArray[28];
String s29 = trainInfoArray[29];
String s30 = trainInfoArray[30];
String s31 = trainInfoArray[31];
String s32 = trainInfoArray[32];
TrainInfo info = new TrainInfo(trainNo, formTime, arrivalTime, s23, s26, s28, s29, s30, s31, s32);
myModel.addData(info);
}
table.updateUI();
}
});
jb_questTicket.setBounds(695, 41, 93, 23);
contentPane.add(jb_questTicket);

JButton jb_vieforTicket = new JButton("刷票");
jb_vieforTicket.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
StringBuffer seatNumber = new StringBuffer();
Component[] seats = seatList.getComponents();
for(int i = 0; i < seatList.getComponentCount(); i++){
if(seats[i] instanceof JCheckBox){
JCheckBox is = (JCheckBox) seats[i];
if(is.isSelected()){
seatNumber.append(judgeSead(is.getText()) + ",");
}
}
}

StringBuffer passengerName = new StringBuffer();
Component[] passengers = passengerList.getComponents();
for(int j = 0; j < passengers.length; j++){
if(passengers[j] instanceof JCheckBox){
JCheckBox is = (JCheckBox) passengers[j];
if(is.isSelected()){
passengerName.append(is.getText() + ",");
}
}
}

String fromStationName = TicketView.this.fromStationName.getText();
String toStationName = TicketView.this.toStationName.getText();
String goTrainDate = TicketView.this.goTrainDate.getText();
String seatNumberStr = seatNumber.deleteCharAt(seatNumber.length() - 1).toString();
String passengerNameStr = passengerName.deleteCharAt(passengerName.length() - 1).toString();
if(fromStationName == null & toStationName == null & goTrainDate == null & seatNumberStr == null & passengerNameStr == null){
return;
}
code.getTicketIn(seatNumberStr, passengerNameStr, fromStationName, toStationName, goTrainDate);
}
});
jb_vieforTicket.setBounds(695, 92, 93, 23);
contentPane.add(jb_vieforTicket);

}

public void initCode(){
code.setPassengerInfo();
}

public class HeroTableModel extends AbstractTableModel{


/**

*/
private static final long serialVersionUID = 1L;

public String[] columnNames = new String[] { "車次", "出發時間", "到達時間", "特等座", "一等座", "二等座", "軟臥", "硬臥", "硬座", "無座"};
public List<TrainInfo> heros = new ArrayList<>();

/**
* 新增資料;
* @param date
*/
public void addData(TrainInfo info){
this.heros.add(info);
}

/**
* 清理資料;
*/
public void clearData(){
this.heros.clear();
}


@Override
public int getRowCount() {
// TODO Auto-generated method stub
return heros.size();
}


@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return columnNames.length;
}


@Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub

//return heros[rowIndex][columnIndex];
TrainInfo info = heros.get(rowIndex);
       if (0 == columnIndex){
       return info.getTrainNo();
       }
       if (1 == columnIndex){
       return info.getFormTime();
       }
       if (2 == columnIndex){
       return info.getArrivalTime();
       }
       if (3 == columnIndex){
       return info.getS32();
       }
       if (4 == columnIndex){
       return info.getS31();
       }
       if (5 == columnIndex){
       return info.getS30();
       }
       if (6 == columnIndex){
       return info.getS23();
       }
       if (7 == columnIndex){
       return info.getS28();
       }
       if (8 == columnIndex){
       return info.getS29();
       }
       if (9 == columnIndex){
       return info.getS26();
       }
       
       return null;
}

//返回列名;
public String getColumnName(int columnIndex) {
       // TODO Auto-generated method stub
       return columnNames[columnIndex];
   }
 
   // 單元格是否可以修改
   public boolean isCellEditable(int rowIndex, int columnIndex) {
       return false;
   }

}

public void printLog(String massage){
this.logInfo.setText(massage + "\n");
}
}

http工具

package com.text.utils;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.