標簽:des class blog img com code div javascript java width art
最近在弄一个微信的公众帐号,涉及到火车票查询,之前用的网上找到的一个接口,但只能查到火车时刻表,12306又没有提供专门的查票的接口。今天突然想起自己直接去12306上查询,抓取查询返回的数据包,这样就可以得到火车票的信息。这里就随笔记一下获取12306余票的过程。
首先,我用firefox浏览器上12306查询余票。打开firefox的Web控制台,选上网络中的“记录请求和响应主体”
然後輸入地址日期信息之後點擊網頁上的查詢按鈕,就能在Web控制台下看到網頁請求的地址了:
就是圖片中的第二條,即當你點擊查詢按鈕時,處理該事件的實際地址。點開它可以看到
請求網址,請求頭,響應頭和響應主體這些東西,響應主體裏就是我們需要的火車票信息。
有了這個請求網址了就可以到實際代碼中進行操作了。可以發現網址的格式是
前面是處理請求的地址,後面接的參數purpose_codes是指成人票(AADULT),學生票(自己去試試吧),queryDate就是日期,from_station和to_station顧名思義就是出發站和到達站了。這裏北京和武漢分別表示爲BJP和WHN。
到java代碼裏就可以直接寫https請求來獲取火車票信息數據包了
public static List<NewTrain> getmsg(String startCity,String endCity,int isAdult) throws Exception{ List<NewTrain> trains = new ArrayList<NewTrain>(); String sstartCity = CityCode.format(startCity); String sendCity = CityCode.format(endCity); TrustManager[] tm = {new MyX509TrustManager()}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對象中得到SSLSocketFactory對象 SSLSocketFactory ssf = sslContext.getSocketFactory(); String type = "ADULT"; if(isAdult == 1){ type = "0X00"; } String urlStr = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes="+type+"&queryDate=2014-04-27&from_station="+sstartCity+"&to_station="+sendCity; URL url = new URL(urlStr); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(ssf); InputStreamReader in = new InputStreamReader(con.getInputStream(),"utf-8"); BufferedReader bfreader = new BufferedReader(in); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = bfreader.readLine()) != null) { sb.append(line); } System.out.println(sb.toString()); }
這段代碼的cityCode.format()是自己寫的將中文的站名轉換爲字母組合,下面那幾行是關于https請求的。網址就是剛才獲取到的網址。這段代碼執行後得到的輸出內容如下:
很容易看出來這些數據是一條條的json數據(我進行了簡單的處理,讓他一條條打印出來)。
既然是json數據就好辦了。取出一條數據來進行分析就可以分析出來key值代表的意思。我只分析了幾個我需要的key值
然後就直接寫一個Train類來儲存火車票的信息,便于之後顯示用了。
public class NewTrain { private String to_station_name; //到達地 private String station_train_code; //火車編號 private String from_station_name; //出發地 private String start_time; //出發時間 private String arrive_time; // 到達時間 private String lishi; // 需要時間 private String zy_num; // 一等座數量 private String ze_num; // 二等座數量 private String swz_num; // 商務座數量 private String gr_num; // 高級軟臥數量 private String rw_num; // 軟臥數量 private String rz_num; // 軟座數量 private String yw_num; // 硬臥數量 private String yz_num; // 硬座數量 private String tz_num; // 特等座數量 private String wz_num; // 無座數量 }
接下來的工作就很簡單了,將json數據放入Train類對象中。
好了,基本工作完成了,接下來的工作就是將功能整合到項目裏去了。
這其中用到的中文站名跟字母組合的一個txt文件(讀txt獲取中文站名對應的字母的組合,有一些可能不全,大家有好的資源可以提供給我一下,謝了~)
如果大家需要可以邮件我376751704@qq.com (第一次写这个不知道怎么上传附件~)
java抓取12306火車余票信息,布布扣,bubuko.com
標簽:des class blog img com code div javascript java width art
原文地址:http://www.cnblogs.com/onlyworld/p/3694698.html