本来是去年打算写的一个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.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.text.cores.Code;

public class MyKeepLineHttpUtil {

public CloseableHttpClient httpClient = null;  
    public HttpClientContext context = null;
    public SSLContext sslContext = null;
    public CookieStore cookieStore = null;  
    public RequestConfig requestConfig = null;
    private HttpHost httpHost = new HttpHost("127.0.0.1", 8888);
    private PoolingHttpClientConnectionManager connectionManager= null;
    
    public MyKeepLineHttpUtil(){
    init();
    }
    
private void init() {

/*
* 设置代理的请求配置;
* requestConfig = RequestConfig.custom().setConnectTimeout(30000)
.setSocketTimeout(60000).setConnectionRequestTimeout(60000)
.setCookieSpec(CookieSpecs.STANDARD).setProxy(httpHost).build();*/
requestConfig = RequestConfig.custom().setConnectTimeout(30000)
.setSocketTimeout(60000).setConnectionRequestTimeout(60000)
.setCookieSpec(CookieSpecs.STANDARD).build();
cookieStore = new BasicCookieStore();
sslContext = getSSLContext();
connectionManager = new PoolingHttpClientConnectionManager(getRegistry());
context = HttpClientContext.create();
context.setCookieStore(cookieStore);

/*httpClient = HttpClientBuilder.create()
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore).build();*/
httpClient = getHttpClient2();
}
    
private SSLConnectionSocketFactory getSocketFactory(){
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{
new X509TrustManager() {

@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub

}

@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {

}
}
}, null);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
return sslConnectionSocketFactory;
}

private SSLContext getSSLContext(){
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sslContext;
}

private class TrustAllManager implements X509TrustManager {
//12306
private Certificate srca_cer = null;
//fidder
private Certificate fidder_cer = null;

public TrustAllManager() {
srca_cer = addCertificate();
fidder_cer = addCertificate2();
}

private Certificate addCertificate(){
Certificate certificate = null;
try {
//System.setOut(new PrintStream(new File("E:/12306_eache/log.txt")));
InputStream resource = this.getClass().getClassLoader().getResourceAsStream("resource/srca.cer");
BufferedInputStream bis = new BufferedInputStream(resource);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

while (bis.available() > 0) {
certificate = cf.generateCertificate(bis);
}
bis.close();
} catch (CertificateException | IOException e) {
e.printStackTrace();
}
return certificate;
}

private Certificate addCertificate2(){
Certificate certificate = null;
try {
/*FileInputStream file = new FileInputStream("E:\\12306_eache\\FiddlerRoot.cer");
BufferedInputStream bis = new BufferedInputStream(file);*/
InputStream resource = this.getClass().getClassLoader().getResourceAsStream("resource/FiddlerRoot.cer");
BufferedInputStream bis = new BufferedInputStream(resource);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
certificate = cf.generateCertificate(bis);
}
bis.close();
} catch (CertificateException | IOException e) {
e.printStackTrace();
}
return certificate;
}

@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{(X509Certificate) srca_cer};
}

}

private Registry<ConnectionSocketFactory> getRegistry(){
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
          .register("http", PlainConnectionSocketFactory.INSTANCE)  
          .register("https", sslConnectionSocketFactory)  
          .build();
return socketFactoryRegistry;
}

/**
     * 获取一个closeableHttpClient;
     * @return
     */
    public CloseableHttpClient getHttpClient(){
    CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore).setSSLSocketFactory(getSocketFactory()).build();
    return httpClient;
    }
    
    public CloseableHttpClient getHttpClient2(){
    //HttpClientBuilder setConnectionManager = HttpClients.custom().setConnectionManager(connectionManager); 
    CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients
.custom()
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore)
.setConnectionManager(connectionManager).build();
System.out.println("创建带证书连接的httpClient");
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建带开证书连接的httpClient失败,现在放回一个普通的httpClient");
httpClient = HttpClientBuilder
.create()
.setKeepAliveStrategy(
new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore).build();
}
    return httpClient;
    }
    
    /**
     * 关闭closeableHttpClient;
     */
public void closeHttpClient(){
if(this.httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

//添加cookies;
    public void setCookieStore(List<String> cookies){
    if(!cookies.isEmpty()){
    for(int i = 0; i < cookies.size(); i ++){
    String cookiesStr = cookies.get(i);
    String [] arraryCookie = cookiesStr.split(",");
    BasicClientCookie cookie = new BasicClientCookie(arraryCookie[0], arraryCookie[1]);
    cookie.setDomain(arraryCookie[2]);
    cookie.setPath(arraryCookie[3]);
    cookieStore.addCookie(cookie);
    }
    }
    }
    
    public Map<String, String> sendGET(String url, String charset){
    Map<String, String> resultMap = new HashMap<String, String>();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
    httpGet.addHeader("Host", "kyfw.12306.cn");
    httpGet.addHeader("Referer", "https://kyfw.12306.cn/otn/regist/init");
    httpGet.addHeader("X-Requested-With", "xmlHttpRequest");
    httpGet.addHeader("Accept", "*/*");
    CloseableHttpResponse response = null;
    try {
response = httpClient.execute(httpGet, context);
cookieStore = context.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {  
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 302){
String location = response.getFirstHeader("Location").getValue();
System.out.println(location);
}
resultMap.put("stateCode", statusCode + "");
HttpEntity entity = response.getEntity();
System.out.println(entity.getContentLength());
            if(entity != null){ 
                String result = EntityUtils.toString(entity, "UTF-8");
                resultMap.put("result", result);
            }
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return resultMap;
    }
    
    public Map<String, String> sendGETByteStream(String url, String charset){
    Map<String, String> resultMap = new HashMap<String, String>();
    BufferedInputStream in = null;
    OutputStream out = null;
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
    response = httpClient.execute(httpGet, context);
    cookieStore = context.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {  
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
HttpEntity entity = response.getEntity();
URL url2 = MyKeepLineHttpUtil.class.getClassLoader().getResource("resource/123.jpg");
System.out.println(url2);
String path = url2.getFile();
path = path.substring(5, path.length());
File file = new File(path);
out = new FileOutputStream(file);
//out = new FileOutputStream(file);
in = new BufferedInputStream(entity.getContent());
byte[] byteArray = new byte[1024 * 10];
int length = 0;
while((length = in.read(byteArray)) != -1){
out.write(byteArray, 0, length);
}
resultMap.put("result", "123.jpg");
int statusCode = response.getStatusLine().getStatusCode();
resultMap.put("stateCode", statusCode + "");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
out.close();
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
    return resultMap;
    }
    
    /**
     * post ģ����ύ;
     * @param url
     * @param param
     * @param charset
     * @return
     */
    public Map<String, String> sendPOST(String url, Map<String, String> param, String charset){
    Map<String, String> resultMap = new HashMap<String, String>();
    HttpPost httpPost = new HttpPost(url);
    List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
    for(Map.Entry<String, String> map:param.entrySet()){
        formparams.add(new BasicNameValuePair(map.getKey(), map.getValue()));
        System.out.println(map.getKey() + "=" + map.getValue());
    }
        
        UrlEncodedFormEntity uefEntity = null;
        httpPost.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
        httpPost.addHeader("Host", "kyfw.12306.cn");
        httpPost.addHeader("Referer", "https://kyfw.12306.cn/otn/regist/init");
        httpPost.addHeader("X-Requested-With", "xmlHttpRequest");
        httpPost.addHeader("Accept", "*/*");
        CloseableHttpResponse response = null;
       
        try {
        uefEntity = new UrlEncodedFormEntity(formparams, charset);
        httpPost.setEntity(uefEntity);
        response = httpClient.execute(httpPost, context);
            cookieStore = context.getCookieStore();  
            List<Cookie> cookies = cookieStore.getCookies();  
            for (Cookie cookie : cookies) {  
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 302){
String location = response.getFirstHeader("Location").getValue();
System.out.println(location);
}
resultMap.put("stateCode", statusCode + "");
            HttpEntity entity = response.getEntity();   
            if(entity != null){ 
                String result = EntityUtils.toString(entity, "UTF-8");
                resultMap.put("result", result);
            }
            
        }catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {  
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
        }
        return resultMap;
    }
    
    /**
     * POST ����json���ݸ�ʽ;
     * @param url
     * @param param
     * @param charset
     * @return
     */
    public Map<String, String> sendPOST(String url, String param, String charset){
    Map<String, String> resultMap = new HashMap<String, String>();
    HttpPost httpPost = new HttpPost(url);
    StringEntity json = new StringEntity(param, charset);
    json.setContentEncoding("UTF-8");    
    json.setContentType("application/json");
    httpPost.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
    httpPost.addHeader("Host", "kyfw.12306.cn");
    httpPost.addHeader("Referer", "https://kyfw.12306.cn/otn/regist/init");
    httpPost.addHeader("X-Requested-With", "xmlHttpRequest");
    httpPost.addHeader("Accept", "*/*");
    httpPost.setEntity(json);
    CloseableHttpResponse response = null;
    try {
    response = httpClient.execute(httpPost, context);
    List<Cookie> cookies = cookieStore.getCookies();
    for (Cookie cookie : cookies) {  
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
    int statusCode = response.getStatusLine().getStatusCode();
resultMap.put("stateCode", statusCode + "");
            HttpEntity entity = response.getEntity(); 
            if(entity != null){ 
                String result = EntityUtils.toString(entity, "UTF-8");
                resultMap.put("result", result);
            }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
   
    return resultMap;
    }

public static void main(String[] args) {
    MyKeepLineHttpUtil httpUtil = new MyKeepLineHttpUtil();
    Map<String, String> sendGET = httpUtil.sendGET("https://kyfw.12306.cn/otn/login/init", "utf-8");
    System.out.println(sendGET.get("stateCode"));
    System.out.println(sendGET.get("result"));
   
}

}

最后

好了!

新手写的一个12306刷票工具相关推荐

  1. Python selenium+pyautogui写的一个12306抢票

    用selenium+pyautogui写的一个12306抢票 `` 最近处于找工作阶段,在家里闲着无聊,写了一个12306的抢票,还很简陋,也是第一次写文发帖,大佬勿喷. 首先导入模块部分.有些外部库 ...

  2. 闲来无事写了一个便笺小工具。

    一直使用TXQQ的便笺工具,突然这几天发现没有这个功能了. 于是自己写了一个. 能实现基本的功能. 1.关闭时自动保存便签上的内容.下次打开还是该内容 2.靠近最上侧和最右侧时自动隐藏.鼠标靠近时自动 ...

  3. 怎么用python编写个apk_新手用tkinter写了一个APK提取工具

    [Python] 纯文本查看 复制代码""" @author:qh @datetime:2019-3-15 @mood:<(* ̄▽ ̄*)/ "" ...

  4. 动手写了一个12306插件 chrome浏览器

    2019独角兽企业重金招聘Python工程师标准>>> 小生是今年毕业来上海参加工作的一位很普通的java web程序员,后经人介绍转到SAP方向. 以前大学离家相对比较近,都是坐汽 ...

  5. 用Python写的一个monkeyrunner小工具(支持手机截图与定时截图,手机屏幕的显示)

    做软件测试刚好一年了,虽让测试对代码的要求不高,但自己也挺喜欢写代码的 最经在闲暇的时间做了一个monkeyrunner的小工具,支持手机屏幕的动态显示,截图以及定时截图,分享一下: 资源下载地址: ...

  6. 【Python脚本抢红包】用Python写了一个自动抢红包工具,今年过年准备大干一场

    话说又要过年了,现在过年可没有小时候的味道了,小时候只顾着放鞭炮,现在只顾着各个群里蹲红包. 但是手动抢肯定没戏,毕竟手can谁也没办法!那就只能试试能不能通过编程的方式实现自动化抢红包了! 跟小编一 ...

  7. python 写的一个按键精灵工具 特别方便 喜欢拿去

    程序可以每隔固定周期时间自动进行操作鼠标.键盘.输入文本等. 屏幕坐标我是用FastStoneCapture软件的"屏幕十字线"功能取的,很方便,其实方法很多,屏幕截图用画图软件也 ...

  8. html病毒编写,用bat写的一个小病毒

    用了三天才看完=.=,感觉作者整理整理可以把博客当书买了... 然后自己突发其想,想到了一个小病毒程序,其实也算不上病毒,只能算是个恶作剧程序吧,其原理就是不断打开cmd程序,占用系统资源...呵呵. ...

  9. ❤️女朋友桌面文件杂乱无章?气得我用Python给她做了一个文件整理工具❤️

    先看效果图 文章目录 写在前面 文件整理功能 实现 GUI 界面 设置界面主题样式 添加选择路径组件及功能实现 添加"整理","撤销"组件及功能实现 添加输出框 ...

  10. 写了一个测试正则表达式的小工具

    这两天写了两个蜘蛛程序用来自动下载漫画,许多时候都是用他在网页中通过正则表达式获取关键字和信息.我用的正则表达式的工具是Expresso,这个工具无疑是目前最好的正则表达式的工具之一.但用着用着就觉得 ...

最新文章

  1. 13种编程语言名称的来历
  2. [LCS]半个月的成果,用RTCClient开发的Robot!
  3. python opencv 图像网络传输
  4. 密码检验规则(字母数字和特殊字符组成的混合体)
  5. NIO 之 FileChannel
  6. Ubuntu16.04/18.04 安装配置JDK 1.8 环境( Linux )
  7. Python 基本输出
  8. Python 文件读和写
  9. html代码type,HTML中type是什么意思
  10. DataGrid分页;指定列的总和和平均值;显示鼠标背景色;弹出式窗口;
  11. [android] android下文件访问的权限
  12. linux中u盘驱动程序编写,Linux下的硬件驱动——USB设备(下)(驱动开发部分)...
  13. java生成顺序流水号_Java生成流水号(1)
  14. 二维数组(动态规划)
  15. transition属性
  16. mysql误删除数据恢复处理
  17. openwrt_ipsec_racoon.init 分析
  18. IPD的决策评审CDP(2):因地制宜,因时而动
  19. mysql备份和优化_MySql Innodb存储引擎--备份和优化
  20. 手机充值时常见问题及解决方法

热门文章

  1. 学习Vue3 第七章(认识Reactive全家桶)
  2. 数学传奇1——群星闪耀时
  3. html 页面长度单位,css绝对长度单位有哪些?
  4. 怎样用 Excel 快速做数据分析?
  5. 13异步多线程(三)Parallel,线程安全
  6. 瀑布流插件masonry
  7. python 正则表达式 compile_使用compile()函数编译正则表达式【Python技术文章】
  8. Audio Hijack教程:轻松捕获iOS设备中的音频
  9. 计算机网络链接密码,怎么连接局域网中计算机网络密码方法介绍
  10. JDK官方下载(旧版本,以前老版本)