有关获取余票信息的票价的问题
Java获取12306余票信息(一)
Java获取12306余票信息(二)
Java获取12306余票信息(三)
API:
https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=5s000G731900&from_station_no=05&to_station_no=08&seat_types=O9MO&train_date=2018-04-03
分析这个api可以看到 train_no
、from_station_no
、to_station_no
、seat_types
、 train_date
五个参数。那么哪里知道这些呢
之前说到过余票信息的json字符串,截取一段看一下
所指的五个分别代表了车次编号,日期,出发站编号,到达站编号,座位类型。发现都有,只要把这几个值拿到并拼接到url里面就行了,上一篇文章说到过怎么通过java代码获取json数据并进行处理,在这里就不多说了,主要是分析这个json。
json:
我们看一下票价信息的json是什么样子的
车次编号还有票价信息都在这儿,不难分析出WZ,M这些字符代表了不同座位类型的价格,博主想在网上找OT,WZ这些代表啥但是没有找到,于是就一条一条的分析json,最终总结出来以下的信息:
WZ:无座;
A1:硬座
A2:软座
A3:硬卧
A4:软卧
A6:高级软卧
F:动卧
O:二等座
M:一等座
P/A9:商务座
代码处理:
getPrice()方法:
public static JSONObject getPrice(TicketingBean tickets) throws Exception {
String urlStr="https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no="+tickets.getTrain_no()
+"&from_station_no="+tickets.getFrom_station_no()
+"&to_station_no="+tickets.getTo_station_no()
+"&seat_types="+tickets.getSeat_types()
+"&train_date="+tickets.getTrain_date();
String priceString = returnJson(urlStr);
JSONObject jsonObject = JSONObject.fromObject(priceString);
JSONObject jsonObjectPrice = jsonObject.getJSONObject("data");
return jsonObjectPrice;
}
此方法用于获取票价json,获取json的方法上一篇有详细提到,欢迎点击。
PriceBean类
private String WZ;//无座
private String A1;//硬座
private String A2;//软座
private String A3;//硬卧
private String A4;//软卧
private String A6;//高级软卧
private String F;//动卧
private String O;//二等座
private String M;//一等座
private String A9;//商务座
private String P;//商务座
get(),set(),toString()方法自行实现;
selectPrice()方法
public static List<PriceBean> selectPrice(TicketingBean tickets) throws Exception {
Map<String,String> priceMap ;
PriceBean priceBean = new PriceBean();
priceMap=getPrice(tickets);//将json对象转换为Map
if(priceMap.get("WZ") != null)//如果不为空,存入javabean
priceBean.setWZ(priceMap.get("WZ"));
if(priceMap.get("A1") != null)
priceBean.setA1(priceMap.get("A1"));
if(priceMap.get("A2") != null)
priceBean.setA2(priceMap.get("A2"));
if(priceMap.get("A3") != null)
priceBean.setA3(priceMap.get("A3"));
if(priceMap.get("A4") != null)
priceBean.setA4(priceMap.get("A4"));
if(priceMap.get("A6") != null)
priceBean.setA6(priceMap.get("A6"));
if(priceMap.get("F") != null)
priceBean.setF(priceMap.get("F"));
if(priceMap.get("O") != null)
priceBean.setO(priceMap.get("O"));
if(priceMap.get("M") != null)
priceBean.setM(priceMap.get("M"));
if(priceMap.get("P") != null)
priceBean.setP(priceMap.get("P"));
if(priceMap.get("A9") != null)
priceBean.setA9(priceMap.get("A9"));
List<PriceBean> listPrice = new ArrayList<>();
listPrice.add(priceBean);
return listPrice;
}
最后就是对POJO的操作了,想怎么操作怎么操作啦
完结
到此就结束了,这篇文章主要是接上一篇查询余票信息的。