從零實現一款12306搶票軟體

范蠡同學發表於2018-11-17

寫在前面的話

每年逢年過節,一票難求讀者肯定不陌生。這篇文章,我們帶領讀者從零實現一款12306刷票軟體,其核心原理還是通過傳送http請求模擬登入12306網站的購票的過程,最後買到票。

關於http請求的格式和如何組裝http資料包給伺服器傳送請求,我們在上一篇文章《從零實現一個http伺服器》(blog.csdn.net/analogous_l…)中已經詳細介紹過了,如果還不明白的朋友可以去那篇文章看下。

鄭重申明一下:這裡介紹的技術僅供用於學習,不可用於惡意攻擊12306伺服器,請勿濫用本文介紹的技術。對12306伺服器造成的任何損失,後果自負。

當然,由於12306伺服器使用者量巨大,為了防止黃牛和其他一些非法攻擊者,12306的很多url和在購票過程中各個步驟的協議細節經常發生變化。所以,本文中介紹的一些具體的url,可能在你看到本文時已經失效。但是這並沒有關係,只要你掌握了本文中介紹的分析方法,您就可以靈活地修改您的程式碼,以適應最新的12306伺服器的要求。舉個例子,如12306的查票介面目前的url是:kyfw.12306.cn/otn/leftTic…,可能過幾天就變成了kyfw.12306.cn/otn/leftTic…,再過幾天又可能變成kyfw.12306.cn/otn/leftTic…,然後一個星期後又可能變成kyfw.12306.cn/otn/leftTic…,這些筆者都見過。所以,重在原理的學習,掌握了原理,不管12306的相關url變成什麼樣,都可以以不變應萬變。哎,12306在與黃牛鬥爭的路上越走越遠啊。T_T

本文將使用以下工具來分析12306購票的過程,然後使用C++語言,模擬相關的過程,最終購票。

  1. Chrome瀏覽器(其他的瀏覽器也可以,都有類似的介面,如Chrome,裝了httpwatch的IE瀏覽器等)

  2. 一個可以登入12306網址並且可以購票的12306賬號

  3. Visual Studio(版本隨意,我這裡用的是VS 2013)

一、查票與站點資訊介面

之所以先分析這個介面,是因為查票不需要使用者登入的,相對來說最簡單。我們在Chrome瀏覽器中開啟12306餘票查詢頁面,網址是:kyfw.12306.cn/otn/leftTic…,如下圖所示:

從零實現一款12306搶票軟體

然後在頁面中右鍵選單中選擇【檢查】選單,開啟後,選擇【網路】選項卡。如下圖所示:

從零實現一款12306搶票軟體

從零實現一款12306搶票軟體

開啟後頁面變成二分視窗了,左側是正常的網頁頁面,右側是瀏覽器自帶的控制檯,當我們在左側頁面中進行操作後,右側會顯示我們瀏覽器傳送的各種http請求和應答。我們這裡隨便查一個票吧,如查2018年5月20日從上海到北京的票,點選查詢後,我們發現右側是這樣的:

從零實現一款12306搶票軟體

通過圖中列表的type值是xhr,我們可以得出這是一個ajax請求(ajax是瀏覽器原生支援的一種非同步請求,詳情請自行百度)。我們選擇這個請求,你能看到這個請求的細節——請求和響應結果:

從零實現一款12306搶票軟體

在reponse中,我們可以看到我們的這個http的去除http頭的響應結果:

從零實現一款12306搶票軟體

這是一個json格式,我們找個json格式化工具,把這個json格式化後貼出來給大家看一下,其實您後面會發現12306的http請求結果中與購票相關的資料基本上都是json格式。這裡的json如下:

{
	"validateMessagesShowId": "_validatorMessage",
	"status": true,
	"httpstatus": 200,
	"data": {
		"result": ["null|23:00-06:00系統維護時間|5l0000G10270|G102|AOH|VNP|AOH|VNP|06:26|12:29|06:03|IS_TIME_NOT_BUY|RLVVIt093U2EZuy2NE+VQyRloXyqTzFp6YyNk6J52QcHEA01|20180520|3|HZ|01|11|1|0|||||||||||1|有|13||O090M0|O9M|0", "null|23:00-06:00系統維護時間|5l0000G10470|G104|AOH|VNP|AOH|VNP|06:40|12:33|05:53|IS_TIME_NOT_BUY|j/TM45GgyJRRKvdalo3VIal8nYF7Hy9VL6njjGX3nOR3xwIu|20180520|3|HZ|01|09|1|0|||||||||||2|有|15||O090M0|O9M|0", "null|23:00-06:00系統維護時間|55000000G600|G6|SHH|VNP|SHH|VNP|07:00|11:38|04:38|IS_TIME_NOT_BUY|SO6mCijnVzhdTrntsbeMoJ4Vuw/WsAnsBz80diva/wuIfsS5|20180520|3|H1|01|05|1|0|||||||||||1|5|8||O090M0|O9M|0", "null|23:00-06:00系統維護時間|5l0000G106A0|G106|AOH|VNP|AOH|VNP|07:12|13:13|06:01|IS_TIME_NOT_BUY|Limy8VLpKgfmzb1EJZ0G7P8/Ai5iR7qbbwhplNeOVIxLQYab|20180520|3|HY|01|11|1|0|||||||||||1|11|12||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G10870|G108|AOH|VNP|AOH|VNP|07:22|13:23|06:01|IS_TIME_NOT_BUY|OJIuMonF9ctgAxxDpZRkNy0fn4HrG8Y+6ThVIAxtGrCWIp0N|20180520|3|HY|01|12|1|0|||||||||||無|6|3||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G110B0|G110|AOH|VNP|AOH|VNP|07:28|13:38|06:10|IS_TIME_NOT_BUY|HVY2cA5DQzMC1VDiotEG4zXAOwG4fHHYq2bh1ZFhm47pySly|20180520|3|HY|01|11|1|0|||||||||||無|5|13||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G120S0|G120|AOH|VNP|AOH|VNP|07:51|13:33|05:42|IS_TIME_NOT_BUY|G2C5o+MADORl4B9HQ2jmTdT2+fBnCbCXvfKCjqf0Fmm6fbU2|20180520|3|H6|01|08|1|0|||||||||||無|有|10||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l000000G814|G8|AOH|VNP|AOH|VNP|08:00|12:24|04:24|IS_TIME_NOT_BUY|dEqPPAVH6ICSdUQQwQ1ry/Ns0+QJCE2N+EZd4oC7FOmz855B|20180520|3|H6|01|04|1|0|||||||||||4|4|9||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G11293|G112|AOH|VNP|AOH|VNP|08:05|14:08|06:03|IS_TIME_NOT_BUY|j1BM0nZuw/phl6Z7WFxg0kFAc5Z4t+qKWZe3fjKB5ZR72nLl|20180520|3|HY|01|11|1|0|||||||||||無|3|2||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G11470|G114|AOH|VNP|AOH|VNP|08:15|14:13|05:58|IS_TIME_NOT_BUY|OwWGlKxfnPfPYGOuhjVhioA2r3kj2krs0zxNVD04+IDhPhfc|20180520|3|HY|01|11|1|0|||||||||||無|1|無||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l000000G232|G2|AOH|VNP|AOH|VNP|09:00|13:28|04:28|IS_TIME_NOT_BUY|8Q4veHYksOBLKJU03KPa0jbPDTgUByjp+UFMScwuarKvhZ+F|20180520|3|HY|01|04|1|0|||||||||||無|5|1||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G11670|G116|AOH|VNP|AOH|VNP|09:33|15:23|05:50|IS_TIME_NOT_BUY|jsCsXdkuWHZVgZ0YzaO+zWokRnnDQ4zowg78aRmc/hzNEMjK|20180520|3|HY|01|10|1|0|||||||||||無|6|2||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G11860|G118|AOH|VNP|AOH|VNP|24:00|24:00|99:59|IS_TIME_NOT_BUY||20180520||H6|01|11|0|1|||||||||||||||||0", "null|23:00-06:00系統維護時間|5l00000G1001|G10|AOH|VNP|AOH|VNP|10:00|14:28|04:28|IS_TIME_NOT_BUY|ycAb36mk9wXaSIll0bTc5WbH8wLT1YRVjvGH/cYzAxIoVMcU|20180520|3|H1|01|04|1|0|||||||||||無|無|5||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5600000G4280|G42|HGH|VNP|AOH|VNP|10:26|16:08|05:42|IS_TIME_NOT_BUY|usY+Ul57hWKitIUp1d4m3n3e0ys4iJTdDfedKU6oXk7F3bAb|20180520|3|H6|04|13|1|0|||||||||||無|無|無||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G12290|G122|AOH|VNP|AOH|VNP|10:41|16:43|06:02|IS_TIME_NOT_BUY|tNu43MkXqpjkcIe80jbPhpSgQ3IOcIyLbwMSspllz0Btc3mJ|20180520|3|H6|01|12|1|0|||||||||||無|5|3||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G124V0|G124|AOH|VNP|AOH|VNP|11:00|16:18|05:18|IS_TIME_NOT_BUY|otn+9ShYEtsJ+6yDQexyyomS8daAeRrvr958XuZ8C4hldEB1|20180520|3|H6|01|06|1|0|||||||||||1|8|3||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G126B0|G126|AOH|VNP|AOH|VNP|11:05|17:05|06:00|IS_TIME_NOT_BUY|HIpEbr9n0fqeUtQGaASOBoD+/duc8JM5U1M602j0rnrf0XfA|20180520|3|H6|01|12|1|0|||||||||||4|8|無||O090M0|O9M|0", "null|23:00-06:00系統維護時間|5l0000G128N0|G128|AOH|VNP|AOH|VNP|24:00|24:00|99:59|IS_TIME_NOT_BUY||20180520||H1|01|12|0|1|||||||||||||||||0", "null|23:00-06:00系統維護時間|5l0000G13080|G130|AOH|VNP|AOH|VNP|11:20|17:29|06:09|IS_TIME_NOT_BUY|eaISX27C/T247JdvbJCFWkXvFimDh4W5rNAht1O5/1PhCbLN|20180520|3|H1|01|13|1|0|||||||||||無|無|2||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5500000G1200|G12|SHH|VNP|SHH|VNP|12:00|16:38|04:38|IS_TIME_NOT_BUY|GxssVQj1spkQVDnyUYodUASXXdwKUnuMjltjIAMwB2IbtIxC|20180520|3|H1|01|04|1|0|||||||||||無|無|無||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G132C0|G132|AOH|VNP|AOH|VNP|12:17|18:32|06:15|IS_TIME_NOT_BUY|2obvVTZf5/iiIKfTAkXU8tDIK4dMypDrpaoQO0WhfqKp3b5h|20180520|3|H1|01|13|1|0|||||||||||無|2|4||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5500001462I0|1462|SHH|BJP|SHH|BJP|12:18|10:46|22:28|IS_TIME_NOT_BUY|05Xf+SuYrrrVUcoitze9/BO1a6zlhm/43WFiXQjDEU7Z+hbDUoKqD2myF3Y=|20180520|3|H2|01|23|0|0||||2|||有||無|有|||||10401030|1413|0", "null|23:00-06:00系統維護時間|5l0000G41250|G412|AOH|VNP|AOH|VNP|12:28|18:48|06:20|IS_TIME_NOT_BUY|CtWjFYsZE3ih/LiOPF03WQb8CvMe6jwdlqUwBRxKn3yRAn9F|20180520|3|H2|01|11|1|0|||||||||||無|2|2||O090M0|O9M|0", "null|23:00-06:00系統維護時間|5l0000G134B0|G134|AOH|VNP|AOH|VNP|13:01|18:58|05:57|IS_TIME_NOT_BUY|AO3hxVofuYXk7l6EhzGCCEu4ZHPpS/0A/nkroM7xlpx/fIIX|20180520|3|H6|01|11|1|0|||||||||||3|6|12||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G136O0|G136|AOH|VNP|AOH|VNP|24:00|24:00|99:59|IS_TIME_NOT_BUY||20180520||H6|01|11|0|1|||||||||||||||||0", "null|23:00-06:00系統維護時間|5l0000G13860|G138|AOH|VNP|AOH|VNP|13:30|19:28|05:58|IS_TIME_NOT_BUY|qgHsrIv2ECcib/ImiXBHGt9Vis0yzPG8bKHoOZ0RgY7aE5sK|20180520|3|H6|01|12|1|0|||||||||||無|8|5||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G14060|G140|AOH|VNP|AOH|VNP|13:35|19:41|06:06|IS_TIME_NOT_BUY|ERb1/PPb8O6WfX503UB/hvYJsZO74WIYIjQsCisEZ4esappf|20180520|3|H6|01|13|1|0|||||||||||2|無|6||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l000000G432|G4|AOH|VNP|AOH|VNP|14:00|18:28|04:28|IS_TIME_NOT_BUY|2x7UHKlapgd4OJrubhQIW25wn5ZyA0jvumVcUSzkWJZu+9yr|20180520|3|H6|01|04|1|0|||||||||||無|3|1||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G14253|G142|AOH|VNP|AOH|VNP|14:10|20:18|06:08|IS_TIME_NOT_BUY|LuImd+o+UIDry0/CjwMAzgBtvfwyN4dSpjzXZnTQxN89PqQk|20180520|3|H6|01|11|1|0|||||||||||1|7|9||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G144M3|G144|AOH|VNP|AOH|VNP|14:40|20:29|05:49|IS_TIME_NOT_BUY|xNsqS1nHci52T9o6E1hU3epRaV9cHSpKnl6i+5+2sWsHHOZQ|20180520|3|H6|01|10|1|0|||||||||||1|2|5||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G146F0|G146|AOH|VNP|AOH|VNP|14:52|20:48|05:56|IS_TIME_NOT_BUY|jAmoXkDA3YgUo4lorosGtKbjeNZ15a764hrcb9URyVEUCWBU|20180520|3|H6|01|10|1|0|||||||||||1|6|13||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l00000G1442|G14|AOH|VNP|AOH|VNP|15:00|19:36|04:36|IS_TIME_NOT_BUY|VyN8KW3DEeWDipXBnZoMhHHVf6m6YwwJ3QT5GnlQqbQPFOCK|20180520|3|H6|01|05|1|0|||||||||||2|2|1||O090M0|O9M|0", "null|23:00-06:00系統維護時間|5l0000G148D0|G148|AOH|VNP|AOH|VNP|15:23|21:13|05:50|IS_TIME_NOT_BUY|v4DRs/7cxkGkWywbOoZYi/lM8FMuYWVO31zuFqaoPsWzuk2N|20180520|3|H6|01|11|1|0|||||||||||無|有|4||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G17000|G170|AOH|VNP|AOH|VNP|15:52|21:18|05:26|IS_TIME_NOT_BUY|OwWGlKxfnPfPYGOuhjVhioA2r3kj2krs0zxNVD04+IDhPhfc|20180520|3|H1|01|08|1|0|||||||||||無|1|無||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G15060|G150|AOH|VNP|AOH|VNP|16:05|22:00|05:55|IS_TIME_NOT_BUY|B+kl5hvzm26b184g8odo4t15OHC22ban1A1nGGF301bDERGO|20180520|3|H6|01|10|1|0|||||||||||1|有|8||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G152E0|G152|AOH|VNP|AOH|VNP|16:18|22:12|05:54|IS_TIME_NOT_BUY|81VzXPX7cSnMfNL08HCNwU+u50GpJ+QNOZctnNmnxXE8onhQ|20180520|3|H6|01|10|1|0|||||||||||無|有|15||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l00000G1613|G16|AOH|VNP|AOH|VNP|17:00|21:36|04:36|IS_TIME_NOT_BUY|1Tjp2E11rAd8KSvlP8BLxwfyqQNNurrS6nFPFNIumUhIkIX3|20180520|3|H6|01|05|1|0|||||||||||1|無|4||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G15470|G154|AOH|VNP|AOH|VNP|17:13|22:48|05:35|IS_TIME_NOT_BUY|FMIX4FHuTLpNf0wPQlJhJvoLN5kawBBXSs2PWGQJ/422H0c0|20180520|3|H6|01|08|1|0|||||||||||無|有|5||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G156R0|G156|AOH|VNP|AOH|VNP|17:18|22:58|05:40|IS_TIME_NOT_BUY|wnJtQjVkFz37b4Xp1eP4obJTdrV9ioOqRUvqvJzy7+AYI7YL|20180520|3|H6|01|09|1|0|||||||||||1|有|17||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5600000G44B0|G44|HGH|VNP|AOH|VNP|17:23|23:08|05:45|IS_TIME_NOT_BUY|4M/BToLy7SoKriz9NLnM6EZwyFF9Tt//rrPb6JCTSb6DtMgW|20180520|3|H6|04|13|1|0|||||||||||8|無|1||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G158C0|G158|AOH|VNP|AOH|VNP|17:34|23:29|05:55|IS_TIME_NOT_BUY|3qcvQyDRKrXX2hJGyupGQxH/evCUFK0TJKN6KMqh8Lzyu/dQ|20180520|3|H6|01|10|1|0|||||||||||1|有|15||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l0000G160V0|G160|AOH|VNP|AOH|VNP|17:44|23:48|06:04|IS_TIME_NOT_BUY|Fs4rA/vbQ+b+MOZP5UK4sCe4nmEcE9xJsA1SywdMcZ2otlav|20180520|3|H6|01|10|1|0|||||||||||有|有|有||O0M090|OM9|0", "null|23:00-06:00系統維護時間|5l00000G1829|G18|AOH|VNP|AOH|VNP|18:00|22:36|04:36|IS_TIME_NOT_BUY|NEuxbLCppnaF8Fm+wuVXDFCSMsVBbOGsCrawCMD/YLarh6s3|20180520|3|H6|01|05|1|0|||||||||||1|5|4||O0M090|OM9|0", "null|23:00-06:00系統維護時間|550000T11061|T110|SHH|BJP|SHH|BJP|18:02|09:30|15:28|IS_TIME_NOT_BUY|Zqy8vHHz4tA2WNH/H1f8d2PE0pc2k+48QoX2hffwrKeUU8zTljDvKT0kSNLlww66AJUR/1v6ckE=|20180520|3|H3|01|09|0|0||無||無|||有||2|1|||||1040106030|14163|0", "null|23:00-06:00系統維護時間|5l00000G2219|G22|AOH|VNP|AOH|VNP|19:00|23:18|04:18|IS_TIME_NOT_BUY|pbuRJ1NgYwLV0f1B6kNwLT1sMCL9o/+CDoQJ6vd1Kbe3GP+1|20180520|3|H6|01|03|1|0|||||||||||6|3|5||O0M090|OM9|0", "null|23:00-06:00系統維護時間|550000D31270|D312|SHH|VNP|SHH|VNP|19:10|07:07|11:57|IS_TIME_NOT_BUY|QNf6TCZV01wG6pmiy2gz3lg/QUAA/Uvm|20180520|3|H3|01|04|0|0||||5||||||||||1|F040|F4|1", "null|23:00-06:00系統維護時間|550000D32260|D322|SHH|VNP|SHH|VNP|19:53|07:45|11:52|IS_TIME_NOT_BUY|xtuqf0inq39vWyfVaA6GfBad2dPnjBk6|20180520|3|H3|01|03|0|0||||有|||||||無||||O040|O4|0", "null|23:00-06:00系統維護時間|550000D31490|D314|SHH|VNP|SHH|VNP|21:07|08:55|11:48|IS_TIME_NOT_BUY|Lamvi3Rs8Nk3cxG7zey21PJvsuzo7v5O|20180520|3|H3|01|04|0|0||||有|||||||5||||O040|O4|0"],
		"flag": "1",
		"map": {
			"AOH": "上海虹橋",
			"BJP": "北京",
			"VNP": "北京南",
			"SHH": "上海"
		}
	},
	"messages": [],
	"validateMessages": {}
}
複製程式碼

其中含有的餘票資訊在result節點中,這是一個陣列。每個節點以|分割,我們可以格式化後顯示在自己的介面上:

從零實現一款12306搶票軟體

我這裡做的介面比較簡陋,讀者如果有興趣可以做更精美的介面。我們列下這個請求傳送的http資料包和應答包:

請求包:

GET /otn/leftTicket/query?leftTicketDTO.train_date=2018-05-20&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=BJP&purpose_codes=ADULT HTTP/1.1
Host: kyfw.12306.cn
Connection: keep-alive
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
If-Modified-Since: 0
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Referer: https://kyfw.12306.cn/otn/leftTicket/init
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_fromDate=2018-05-20; _jc_save_toDate=2018-05-19; _jc_save_wfdc_flag=dc
複製程式碼

應答包:

HTTP/1.1 200 OK
Date: Sat, 19 May 2018 15:23:58 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
ct: C1_217_85_8
Content-Encoding: gzip
Age: 1
X-Via: 1.1 houdianxin183:6 (Cdn Cache Server V2.0)
Connection: keep-alive
X-Dscp-Value: 0
X-Cdn-Src-Port: 33963
Cache-Control: no-cache, no-store
複製程式碼

通過上一篇文章《從零實現一個http伺服器》》(blog.csdn.net/analogous_l…)我們知道這是一個http GET請求,其中在url後面是請求附帶的引數:

leftTicketDTO.train_date: 2018-05-20
leftTicketDTO.from_station: SHH
leftTicketDTO.to_station: BJP
purpose_codes: ADULT
複製程式碼

這四個引數分別是購票日期、出發站、到達站和票型別(這裡是成人票(普通票)),正好對應我們介面上的查詢資訊:

從零實現一款12306搶票軟體

但是,讀者可能會問,這裡的出發站和到達站分別是SHH和BJP,這些站點程式碼,我如何獲得呢?因為只有知道這些站點編碼我才能自己購買指定出發站和到達站的火車票啊。如果您是一位細心的人,您肯定會想到,我們查票的時候再進入查票頁面,這些站點資訊就已經有了,那麼可能是在這個查票頁面載入時,從伺服器請求的站點資訊,所以我們重新整理下查票頁面,發現果然是這樣:

從零實現一款12306搶票軟體

進入查票頁面之前,瀏覽器從kyfw.12306.cn/otn/resourc…下載一個叫station.name.js檔案,這是一個javascript指令碼,裡面只有一行程式碼,就是定義了一個station_names的js變數,之所以url地址後面加一個station_version=1.9053,你可以理解成版本號,但是主要是通過一個隨機值1.9053,讓瀏覽器不要使用快取中的station_name.js,而是每次都從伺服器重新載入下這個檔案,這樣的話如果站點資訊有更新,也可以避免因為快取問題,導致本地的快取與伺服器上的站點資訊不一致。由於站點資訊比較多,我們截個圖吧:

從零實現一款12306搶票軟體

看上圖,我們可以看出來,每個站點資訊都是通過@符號分割,然後通過|分割每一個站點的各種資訊。這樣的話,根據上文的格式假如我們要查詢2018年5月30日從長春到南京的火車普通票,就可以通過網址kyfw.12306.cn/otn/leftTic…

當然,這裡需要說明一下的就是,由於全國的火車站點資訊檔案比較大,我們程式解析起來時間較長,加上火車站編碼資訊並不是經常變動,所以,我們我們沒必要每次都下載這個station_name.js,所以我在寫程式模擬這個請求時,一般先看本地有沒有這個檔案,如果有就使用本地的,沒有才發http請求向12306伺服器請求。這裡我貼下我請求站點資訊的程式程式碼(C++程式碼):

 /** 
  * 獲取全國車站資訊
  * @param si 返回的車站資訊
  * @param bForceDownload 強制從網路上下載,即不使用本地副本
  */
 bool GetStationInfo(vector<stationinfo>& si, bool bForceDownload = false);
複製程式碼
#define URL_STATION_NAMES   "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9053"
複製程式碼
bool Client12306::GetStationInfo(vector<stationinfo>& si, bool bForceDownload/* = false*/)
{  
    FILE* pfile;
    pfile = fopen("station_name.js", "rt+");
    //檔案不存在,則必須下載
    if (pfile == NULL)
    {
        bForceDownload = true;
    }
    string strResponse;
    if (bForceDownload)
    {
        if (pfile != NULL)
            fclose(pfile);
        pfile = fopen("station_name.js", "wt+");
        if (pfile == NULL)
        {
            LogError("Unable to create station_name.js");
            return false;
        }

        CURLcode res;
        CURL* curl = curl_easy_init();
        if (NULL == curl)
        {
            fclose(pfile);
            return false;
        }

        //URL_STATION_NAMES
        curl_easy_setopt(curl, CURLOPT_URL, URL_STATION_NAMES);
        //響應結果中保留頭部資訊
        //curl_easy_setopt(curl, CURLOPT_HEADER, 1);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
        //設定為不驗證證照和HOST
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

        res = curl_easy_perform(curl);
        bool bError = false;
        if (res == CURLE_OK)
        {
            int code;
            res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
            if (code != 200)
            {
                bError = true;
                LogError("http response code is not 200, code=%d", code);
            }
        }
        else
        {
            LogError("http request error, error code = %d", res);
            bError = true;
        }

        curl_easy_cleanup(curl);

        if (bError)
        {
            fclose(pfile);
            return !bError;
        }

        if (fwrite(strResponse.data(), strResponse.length(), 1, pfile) != 1)
        {
            LogError("Write data to station_name.js error");            
            return false;
        }
        fclose(pfile);
    }
    //直接讀取檔案
    else
    {
        //得到檔案大小
        fseek(pfile, 0, SEEK_END);
        int length = ftell(pfile);
        if (length < 0)
        {
            LogError("invalid station_name.js file");
            fclose(pfile);
        }
        fseek(pfile, 0, SEEK_SET);
        length++;
        char* buf = new char[length];
        memset(buf, 0, length*sizeof(char));
        if (fread(buf, length-1, 1, pfile) != 1)
        {
            LogError("read station_name.js file error");
            fclose(pfile);
            return false;
        }
        strResponse = buf;
        fclose(pfile);
    }


    /*
    返回結果為一個js檔案,
    var station_names = '@bjb|北京北|VAP|beijingbei|bjb|0@bjd|北京東|BOP|beijingdong|bjd|1@bji|北京|BJP|beijing|bj|2"
    */
    //LogInfo("recv json = %s", strResponse.c_str());
    OutputDebugStringA(strResponse.c_str());

    vector<string> singleStation;
    split(strResponse, "@", singleStation);

    size_t size = singleStation.size();
    for (size_t i = 1; i < size; ++i)
    {
        vector<string> v;
        split(singleStation[i], "|", v);
        if (v.size() < 6)
            continue;

        stationinfo st;
        st.code1 = v[0];
        st.hanzi = v[1];
        st.code2 = v[2];
        st.pingyin = v[3];
        st.simplepingyin = v[4];
        st.no = atol(v[5].c_str());

        si.push_back(st);
    }

    return true;
}
複製程式碼

這裡用了一個站點資訊結構體stationinfo,定義如下:

//var station_names = '@bjb|北京北|VAP|beijingbei|bjb|0@bjd|北京東|BOP|beijingdong|bjd|1@bji|北京|BJP|beijing|bj|2
struct stationinfo
{
    string code1;
    string hanzi;
    string code2;
    string pingyin;
    string simplepingyin;
    int no;
};
複製程式碼

因為我們這裡目的是為了模擬http請求做買火車票相關的操作,而不是技術方面本身,所以為了快速實現我們的目的,我們就使用curl庫。這個庫是一個強大的http相關的庫,例如12306伺服器返回的資料可能是分塊的(chunked),這個庫也能幫我們組裝好;再例如,伺服器返回的資料是使用gzip格式壓縮的,curl也會幫我們自動解壓好。所以,接下來的所有12306的介面,都基於我封裝的curl庫一個介面:

/**
 * 傳送一個http請求
 *@param url 請求的url
 *@param strResponse http響應結果
 *@param get true為GET,false為POST
 *@param headers 附帶傳送的http頭資訊
 *@param postdata post附帶的資料    
 *@param bReserveHeaders http響應結果是否保留頭部資訊
 *@param timeout http請求超時時間
 */
 bool HttpRequest(const char* url, string& strResponse, bool get = true, const char* headers = NULL, const char* postdata = NULL, bool bReserveHeaders = false, int timeout = 10);
複製程式碼

函式各種引數已經在函式註釋中寫的清清楚楚了,這裡就不一一解釋了。這個函式的實現程式碼如下:

bool Client12306::HttpRequest(const char* url, 
                              string& strResponse, 
                              bool get/* = true*/, 
                              const char* headers/* = NULL*/, 
                              const char* postdata/* = NULL*/, 
                              bool bReserveHeaders/* = false*/, 
                              int timeout/* = 10*/)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if (NULL == curl)
    {
        LogError("curl lib init error");
        return false;
    }

    curl_easy_setopt(curl, CURLOPT_URL, url);

    //響應結果中保留頭部資訊
    if (bReserveHeaders)
       curl_easy_setopt(curl, CURLOPT_HEADER, 1);
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    //設定為不驗證證照和HOST
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

    //設定超時時間
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
    curl_easy_setopt(curl, CURLOPT_REFERER, URL_REFERER);
    //12306早期版本是不需要USERAGENT這個欄位的,現在必須了,估計是為了避免一些第三方的非法刺探吧。
    //如果沒有這個欄位,會返回
    /*
        HTTP/1.0 302 Moved Temporarily
        Location: http://www.12306.cn/mormhweb/logFiles/error.html
        Server: Cdn Cache Server V2.0
        Mime-Version: 1.0
        Date: Fri, 18 May 2018 02:52:05 GMT
        Content-Type: text/html
        Content-Length: 0
        Expires: Fri, 18 May 2018 02:52:05 GMT
        X-Via: 1.0 PSshgqdxxx63:10 (Cdn Cache Server V2.0)
        Connection: keep-alive
        X-Dscp-Value: 0
     */
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36");
    //不設定接收的編碼格式或者設定為空,libcurl會自動解壓壓縮的格式,如gzip
    //curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip, deflate, br");
    

    //新增自定義頭資訊
    if (headers != NULL)
    {
        //LogInfo("http custom header: %s", headers);
        struct curl_slist *chunk = NULL;        
        chunk = curl_slist_append(chunk, headers);      
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
    }

    if (!get && postdata != NULL)
    {
        //LogInfo("http post data: %s", postdata);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
    }

    LogInfo("http %s: url=%s, headers=%s, postdata=%s", get ? "get" : "post", url, headers != NULL ? headers : "", postdata!=NULL?postdata : "");

    res = curl_easy_perform(curl);
    bool bError = false;
    if (res == CURLE_OK)
    {
        int code;
        res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
        if (code != 200 && code != 302)
        {
            bError = true;
            LogError("http response code is not 200 or 302, code=%d", code);
        }
    }
    else
    {
        LogError("http request error, error code = %d", res);
        bError = true;
    }

    curl_easy_cleanup(curl);

    LogInfo("http response: %s", strResponse.c_str());

   return !bError;
}
複製程式碼

正如上面註釋中所提到的,瀏覽器在傳送http請求時帶的一些欄位,我們不是必須的,如查票介面瀏覽器可能會發以下http資料包:

GET /otn/leftTicket/query?leftTicketDTO.train_date=2018-05-30&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=BJP&purpose_codes=ADULT HTTP/1.1
Host: kyfw.12306.cn
Connection: keep-alive
Cache-Control: no-cache
Accept: */*
X-Requested-With: XMLHttpRequest
If-Modified-Since: 0
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Referer: https://kyfw.12306.cn/otn/leftTicket/init
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: JSESSIONID=ACD9CB098169C4D73CDE80D6F6C38E5A; RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_wfdc_flag=dc; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=1708720394.50210.0000; _jc_save_fromDate=2018-05-30; _jc_save_toDate=2018-05-20
複製程式碼

其中像Connection、Cache-Control、Accept、If-Modified-Since等欄位都不是必須的,所以我們在模擬我們自己的http請求時可以不用可以新增這些欄位,當然據我觀察,12306伺服器現在對傳送過來的http資料包要求越來越嚴格了,如去年的時候,User-Agent這個欄位還不是必須的,現在如果你不帶上這個欄位,可能12306返回的結果就不一定正確。當然,不正確的結果中一定不會有明確的錯誤資訊,充其量可能會告訴你頁面不存在或者系統繁忙請稍後再試,這是伺服器自我保護的一種重要的措施,試想你做伺服器程式,會告訴非法使用者明確的錯誤資訊嗎?那樣不就給了非法攻擊伺服器的人不斷重試的機會了嘛。

需要特別注意的是:查票介面傳送的http協議的頭還有一個欄位叫Cookie,其值是一串非常奇怪的東西:

JSESSIONID=ACD9CB098169C4D73CDE80D6F6C38E5A; RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_wfdc_flag=dc; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=1708720394.50210.0000; _jc_save_fromDate=2018-05-30; _jc_save_toDate=2018-05-2
複製程式碼

在這串字元中有一個JSESSIONID,在不需要登入的查票介面,我們可以傳或者不傳這個欄位值。但是在購票以及查詢常用聯絡人這些需要在已經登入的情況下才能進行的操作,我們必須帶上這個資料,這是伺服器給你的token(驗證令牌),而這個令牌是在剛進入12306站點時,伺服器發過來的,你後面的登入等操作必須帶上這個token,否則伺服器會認為您的請求是非法請求。我第一次去研究12306的買票流程時,即使在使用者名稱、密碼和圖片驗證碼正確的情況下,也無法登入就是這個原因。這是12306為了防止非法登入使用的一個安全措施。

二、登入與拉取圖片驗證碼介面

我的登入頁面效果如下:

從零實現一款12306搶票軟體

12306的圖片驗證碼一般由八個圖片組成,像上面的“龍舟”文字,也是圖片,這兩處的圖片(文字圖片和驗證碼)都是在伺服器上拼裝後,發給客戶端的,12306伺服器上這種型別的小圖片有一定的數量,雖然數量比較大,但是是有限的。如果你要做驗證碼自動識別功能,可以嘗試著下載大部分圖片,然後做統計規律。所以,我這裡並沒有做圖片自動識別功能。有興趣的讀者可自行嘗試。

先說下,拉取驗證碼的介面。我們開啟Chrome瀏覽器12306的登入介面:kyfw.12306.cn/otn/login/i…

從零實現一款12306搶票軟體

可以得到拉取驗證碼的介面:

從零實現一款12306搶票軟體

我們可以看到傳送的http請求資料包格式是:

GET /passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.7520968747611347 HTTP/1.1
Host: kyfw.12306.cn
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: https://kyfw.12306.cn/otn/login/init
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: _passport_session=badc97f6a852499297796ee852515f957153; _passport_ct=9cf4ea17c0dc47b6980cac161483f522t9022; RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_wfdc_flag=dc; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=1708720394.50210.0000; _jc_save_fromDate=2018-05-30; _jc_save_toDate=2018-05-20; BIGipServerpassport=837288202.50215.0000
複製程式碼

這裡也是一個http GET請求,Host、Referer和Cookie這三個欄位是必須的,且Cookie欄位必須帶上上文說的JSESSIONID,下載圖片驗證碼和下文中各個步驟也必須在Cookie欄位中帶上這個JSESSIONID值,否則無法從12306伺服器得到正確的應答。後面會介紹如何拿到這個這。這個拉取圖片驗證碼的http GET請求需要三個引數,如上面的程式碼段所示,即login_site、module、rand和一個類似於0.7520968747611347的隨機值,前三個欄位的值都是固定的,module欄位表示當前是哪個模組,當前是登入模組,所以值是login,後面獲取最近聯絡人時取值是passenger。這裡還有一個需要注意的地方是,如果您驗證圖片驗證碼失敗時,重新請求圖片時,必須也重新請求下JSESSIONID。這個url是https://kyfw.12306.cn/otn/login/init。http請求和應答包如下:

請求包:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Cookie: RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_wfdc_flag=dc; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=1708720394.50210.0000; _jc_save_fromDate=2018-05-30; _jc_save_toDate=2018-05-20; BIGipServerpassport=837288202.50215.0000
Host: kyfw.12306.cn
Referer: https://kyfw.12306.cn/otn/passport?redirect=/otn/login/loginOut
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
複製程式碼

應答包:

HTTP/1.1 200 OK
Date: Sun, 20 May 2018 02:23:53 GMT
Content-Type: text/html;charset=utf-8
Transfer-Encoding: chunked
Set-Cookie: JSESSIONID=D5AE154D66F67DE53BF70420C772158F; Path=/otn
ct: C1_217_101_6
Content-Language: zh-CN
Content-Encoding: gzip
X-Via: 1.1 houdianxin184:4 (Cdn Cache Server V2.0)
Connection: keep-alive
X-Dscp-Value: 0
X-Cdn-Src-Port: 46480
複製程式碼

這個值在應答包欄位Set-Cookie中拿到:

Set-Cookie: JSESSIONID=D5AE154D66F67DE53BF70420C772158F; Path=/otn
複製程式碼

所以,我們每次請求圖片驗證碼時,都重新請求一下這個JSESSIONID,程式碼如下:

#define URL_LOGIN_INIT      "https://kyfw.12306.cn/otn/login/init"
複製程式碼
bool Client12306::loginInit()
{	
    string strResponse;
    if (!HttpRequest(URL_LOGIN_INIT, strResponse, true, "Upgrade-Insecure-Requests: 1", NULL, true, 10))
    {
        LogError("loginInit failed");
        return false;
    }
        
    if (!GetCookies(strResponse))
    {
        LogError("parse login init cookie error, url=%s", URL_LOGIN_INIT);
        return false;
    }
   
    return true;
}
複製程式碼
bool Client12306::GetCookies(const string& data)
{
    if (data.empty())
    {
        LogError("http data is empty");
        return false;
    }
    
    //解析http頭部
    string str;
    str.append(data.c_str(), data.length());
    size_t n = str.find("\r\n\r\n");
    string header = str.substr(0, n);
    str.erase(0, n + 4);
   
    //m_cookie.clear();
    //獲取http頭中的JSESSIONID=21AC68643BBE893FBDF3DA9BCF654E98;
    vector<string> v;
    while (true)
    {
        size_t index = header.find("\r\n");
        if (index == string::npos)
            break;
        string tmp = header.substr(0, index);
        v.push_back(tmp);
        header.erase(0, index + 2);

        if (header.empty())
            break;
    }

    string jsessionid;
    string BIGipServerotn;
    string BIGipServerportal;
    string current_captcha_type;
    size_t m;
    OutputDebugStringA("\nresponse http headers:\n");
    for (size_t i = 0; i < v.size(); ++i)
    {
        OutputDebugStringA(v[i].c_str());
        OutputDebugStringA("\n");
        m = v[i].find("Set-Cookie: ");
        if (m == string::npos)
            continue;

        string tmp = v[i].substr(11);
        Trim(tmp);
        m = tmp.find("JSESSIONID");
        if (m != string::npos)
        {
            size_t comma = tmp.find(";");
            if (comma != string::npos)
                jsessionid = tmp.substr(0, comma);
        }

        m = tmp.find("BIGipServerotn");
        if (m != string::npos)
        {
            size_t comma = tmp.find(";");
            if (comma != string::npos)
                BIGipServerotn = tmp.substr(m, comma);
            else
                BIGipServerotn = tmp;
        }

        m = tmp.find("BIGipServerportal");
        if (m != string::npos)
        {
            size_t comma = tmp.find(";");
            if (comma != string::npos)
                BIGipServerportal = tmp.substr(m, comma);
            else
                BIGipServerportal = tmp;
        }

        m = tmp.find("current_captcha_type");
        if (m != string::npos)
        {
            size_t comma = tmp.find(";");
            if (comma != string::npos)
                current_captcha_type = tmp.substr(m, comma);
            else
                current_captcha_type = tmp;           
        }
    }

    if (!jsessionid.empty())
    {
        m_strCookies = jsessionid;
        m_strCookies += "; ";
        m_strCookies += BIGipServerotn;
        if (!BIGipServerportal.empty())
        {
            m_strCookies += "; ";
            m_strCookies += BIGipServerportal;
        }
        m_strCookies += "; ";
        m_strCookies += current_captcha_type;
        return true;
    }
  
    LogError("jsessionid is empty");
    return false;
}
複製程式碼
#define URL_GETPASSCODENEW  "https://kyfw.12306.cn/passport/captcha/captcha-image"
複製程式碼
bool Client12306::DownloadVCodeImage(const char* module)
{
    if (module == NULL)
    {
        LogError("module is invalid");
        return false;
    }
    
    //https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.06851784300754482
    ostringstream osUrl;
    osUrl << URL_GETPASSCODENEW;
    osUrl << "?login_site=E&module=";
    osUrl << module;
    //購票驗證碼
    if (strcmp(module, "passenger") != 0)
    {
        osUrl << "&rand=sjrand&";
    }
    //登入驗證碼
    else
    {      
        osUrl << "&rand=randp&";     
    }
    double d = rand() * 1.000000 / RAND_MAX;
    osUrl.precision(17);
    osUrl << d;

    string strResponse;
    string strCookie = "Cookie: ";
    strCookie += m_strCookies;
    if (!HttpRequest(osUrl.str().c_str(), strResponse, true, strCookie.c_str(), NULL, false, 10))
    {
        LogError("DownloadVCodeImage failed");
        return false;
    }
  
    //寫入檔案
	time_t now = time(NULL);
    struct tm* tblock = localtime(&now);
    memset(m_szCurrVCodeName, 0, sizeof(m_szCurrVCodeName));
#ifdef _DEBUG
    sprintf(m_szCurrVCodeName, "vcode%04d%02d%02d%02d%02d%02d.jpg",
		1900 + tblock->tm_year, 1 + tblock->tm_mon, tblock->tm_mday,
		tblock->tm_hour, tblock->tm_min, tblock->tm_sec);
#else
    sprintf(m_szCurrVCodeName, "vcode%04d%02d%02d%02d%02d%02d.v",
        1900 + tblock->tm_year, 1 + tblock->tm_mon, tblock->tm_mday,
        tblock->tm_hour, tblock->tm_min, tblock->tm_sec);
#endif

    FILE* fp = fopen(m_szCurrVCodeName, "wb");
    if (fp == NULL)
    {
        LogError("open file %s error", m_szCurrVCodeName);
        return false;
    }

	const char* p = strResponse.data();
    size_t count = fwrite(p, strResponse.length(), 1, fp);
	if (count != 1)
	{
        LogError("write file %s error", m_szCurrVCodeName);
        fclose(fp);
		return false;
	}

	fclose(fp);

	return true;
}
複製程式碼

我們再看下驗證碼去伺服器驗證的介面kyfw.12306.cn/passport/ca…

請求頭:

POST /passport/captcha/captcha-check HTTP/1.1
Host: kyfw.12306.cn
Connection: keep-alive
Content-Length: 50
Accept: application/json, text/javascript, */*; q=0.01
Origin: https://kyfw.12306.cn
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: https://kyfw.12306.cn/otn/login/init
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: _passport_session=3e39a33a25bf4ea79146bd9362c11ad62327; _passport_ct=c5c7940e08ce44db9ad05d213c1296ddt4410; RAIL_EXPIRATION=1526978933395; RAIL_DEVICEID=WKxIYg-q1zjIPVu7VjulZ9PqEGvW2gUB9LvoM1Vx8fa7l3SUwnO_BVSatbTq506c6VYNOaxAiRaUcGFTMjCz9cPayEIc9vJ0pHaXdSqDlujJP8YrIoXbpAAs60l99z8bEtnHgAJzxLzKiv2nka5nmLY_BMNur8b8; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5317%u4EAC%2CBJP; _jc_save_wfdc_flag=dc; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=1708720394.50210.0000; _jc_save_fromDate=2018-05-30; _jc_save_toDate=2018-05-20; BIGipServerpassport=837288202.50215.0000
複製程式碼

這是一個POST請求,其中POST資料帶上的輸入的圖片驗證碼選擇的座標X和Y值:

answer: 175,58,30,51
login_site: E
rand: sjrand
複製程式碼

這裡我選擇了兩張圖片,所以有兩組座標值,(175,58)是一組,(30,51)是另外一組,這個座標系如下:

從零實現一款12306搶票軟體

因為每個圖片的尺寸都一樣,所以,我可以給每個圖片設定一個座標範圍,當選擇了一個圖片,給一個在其中的座標即可,不一定是滑鼠點選時的準確位置:

//重新整理驗證碼 登入狀態下的驗證碼傳入”randp“,非登入傳入”sjrand“ 具體參看原otsweb中的傳入引數
struct VCodePosition
{
    int x;
    int y;
};

const VCodePosition g_pos[] =
{
    { 39, 40 },
    { 114, 43 },
    { 186, 42 },
    { 252, 47 },
    { 36, 120 },
    { 115, 125 },
    { 194, 125 },
    { 256, 120 }
};

//驗證碼圖片八個區塊的位置
struct VCODE_SLICE_POS
{
    int xLeft;
    int xRight;
    int yTop;
    int yBottom;
};

const VCODE_SLICE_POS g_VCodeSlicePos[] = 
{
    {0,   70,  0,  70},
    {71,  140, 0,  70 },
    {141, 210, 0,  70 },
    {211, 280, 0,  70 },
    { 0,  70,  70, 140 },    
    {71,  140, 70, 140 },
    {141, 210, 70, 140 },
    {211, 280, 70, 140 }
};

//8個驗證碼區塊的滑鼠點選狀態
bool g_bVodeSlice1Pressed[8] = { false, false, false, false, false, false, false, false};
驗證的圖片驗證碼的介面程式碼是:

int Client12306::checkRandCodeAnsyn(const char* vcode)
{
    string param;
    param = "randCode=";
    param += vcode;
    param += "&rand=sjrand";	//passenger:randp
    
    string strResponse;
    string strCookie = "Cookie: ";
    strCookie += m_strCookies;
    if (!HttpRequest(URL_CHECKRANDCODEANSYN, strResponse, false, strCookie.c_str(), param.c_str(), false, 10))
    {
        LogError("checkRandCodeAnsyn failed");
        return -1;
    }

	///** 成功返回
	//HTTP/1.1 200 OK
	//Date: Thu, 05 Jan 2017 07:44:16 GMT
	//Server: Apache-Coyote/1.1
	//X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1
	//ct: c1_103
	//Content-Type: application/json;charset=UTF-8
	//Content-Length: 144
	//X-Via: 1.1 jiandianxin29:6 (Cdn Cache Server V2.0)
	//Connection: keep-alive
	//X-Cdn-Src-Port: 19153

	//引數無效
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"0","msg":""},"messages":[],"validateMessages":{}}
	//驗證碼過期
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"0","msg":"EXPIRED"},"messages":[],"validateMessages":{}}
    //驗證碼錯誤
    //{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"1","msg":"FALSE"},"messages":[],"validateMessages":{}}
	//驗證碼正確
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"result":"1","msg":"TRUE"},"messages":[],"validateMessages":{}}
	Json::Reader JsonReader;
	Json::Value JsonRoot;
    if (!JsonReader.parse(strResponse, JsonRoot))
		return -1;
	//{"validateMessagesShowId":"_validatorMessage", "status" : true, "httpstatus" : 200, "data" : {"result":"1", "msg" : "TRUE"}, "messages" : [], "validateMessages" : {}}
	if (JsonRoot["status"].isNull() || JsonRoot["status"].asBool() != true)
		return -1;

	if (JsonRoot["httpstatus"].isNull() || JsonRoot["httpstatus"].asInt() != 200)
		return -1;

	if (JsonRoot["data"].isNull() || !JsonRoot["data"].isObject())
		return -1;

	if (JsonRoot["data"]["result"].isNull())
		return -1;

	if (JsonRoot["data"]["result"].asString() != "1" && JsonRoot["data"]["result"].asString() != "0")
		return -1;

	if (JsonRoot["data"]["msg"].isNull())
		return -1;
	//if (JsonRoot["data"]["msg"].asString().empty())		
	//	return -1;

	if (JsonRoot["data"]["msg"].asString() == "")
		return 0;
	else if (JsonRoot["data"]["msg"].asString() == "FALSE")
		return 1;


	return 1;
}
複製程式碼

同理,這裡也給出驗證使用者名稱和密碼的介面實現程式碼:

int Client12306::loginAysnSuggest(const char* user, const char* pass, const char* vcode)
{
    string param = "loginUserDTO.user_name=";
    param += user;
    param += "&userDTO.password=";
    param += pass;
    param += "&randCode=";
    param += vcode;
    string strResponse;
    string strCookie = "Cookie: ";
    strCookie += m_strCookies;
    if (!HttpRequest(URL_LOGINAYSNSUGGEST, strResponse, false, strCookie.c_str(), param.c_str(), false, 10))
    {
        LogError("loginAysnSuggest failed");
        return 2;
    }

	///** 成功返回
	//HTTP/1.1 200 OK
	//Date: Thu, 05 Jan 2017 07:49:53 GMT
	//Server: Apache-Coyote/1.1
	//X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1
	//ct: c1_103
	//Content-Type: application/json;charset=UTF-8
	//Content-Length: 146
	//X-Via: 1.1 f186:10 (Cdn Cache Server V2.0)
	//Connection: keep-alive
	//X-Cdn-Src-Port: 48361

	//郵箱不存在
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{},"messages":["該郵箱不存在。"],"validateMessages":{}}
	//密碼錯誤
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{},"messages":["密碼輸入錯誤。如果輸錯次數超過4次,使用者將被鎖定。"],"validateMessages":{}}
	//登入成功
	//{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"otherMsg":"",loginCheck:"Y"},"messages":[],"validateMessages":{}}
	//WCHAR* psz1 = Utf8ToAnsi(strResponse.c_str());
	//wstring str = psz1;
	//delete[] psz1;

	Json::Reader JsonReader;
	Json::Value JsonRoot;
    if (!JsonReader.parse(strResponse, JsonRoot))
		return 2;

	//{"validateMessagesShowId":"_validatorMessage", "status" : true, 
	//"httpstatus" : 200, "data" : {"otherMsg":"", loginCheck : "Y"}, "messages" : [], "validateMessages" : {}}
	if (JsonRoot["status"].isNull())
		return -1;

	bool bStatus = JsonRoot["status"].asBool();
	if (!bStatus)
		return -1;

	if (JsonRoot["httpstatus"].isNull() || JsonRoot["httpstatus"].asInt() != 200)
		return 2;

	if (JsonRoot["data"].isNull() || !JsonRoot["data"].isObject())
		return 2;

	if (JsonRoot["data"]["otherMsg"].isNull() || JsonRoot["data"]["otherMsg"].asString() != "")
		return 2;
	if (JsonRoot["data"]["loginCheck"].isNull() || JsonRoot["data"]["loginCheck"].asString() != "Y")
		return 1;

	return 0;
}
複製程式碼

這裡還有個注意細節,就是通過POST請求傳送的資料需要對一些符號做URL Encode,這個我在上一篇文章《從零實現一個http伺服器》(blog.csdn.net/analogous_l…)也詳細做了介紹,還不清楚的可以參見上一篇文章。所以對於向圖片驗證碼座標資訊中含有的逗號資訊就要進行URL編碼,從

answer=114,54,44,46&login_site=E&rand=sjrand
複製程式碼

變成

answer=114%2C54%2C44%2C46&login_site=E&rand=sjrand
複製程式碼

所以,在http包頭中指定的Content-Length欄位的值應該是編碼後的字串長度,而不是原始的長度,這個地方特別容易出錯。

從零實現一款12306搶票軟體

如果驗證成功後,接下來就是查票和購票了。這裡就不一一介紹了,所有的原理都是一樣的,作者可以自行探索。當然,我已經將所有的介面都探索完了,並實現了,我這裡貼一下吧:

/**
 *@desc:	封裝獲取驗證碼、校驗驗證碼、登入等12306各個請求的類,Client12306.h檔案
 *@author:  zhangyl
 *@date:	2017.01.17
 */

#ifndef __CLIENT_12306_H__
#define __CLIENT_12306_H__

#include <vector>
#include <string>

using namespace std;

//車次型別
#define TRAIN_GC     0x00000001
#define TRAIN_D      (0x00000001 << 1)
#define TRAIN_Z      (0x00000001 << 2)
#define TRAIN_T      (0x00000001 << 3)
#define TRAIN_K      (0x00000001 << 4)
#define TRAIN_OTHER  (0x00000001 << 5)
#define TRAIN_ALL    (TRAIN_GC | TRAIN_D | TRAIN_Z | TRAIN_T | TRAIN_K | TRAIN_OTHER)

//票資訊
struct queryLeftNewDTO
{
	string  train_no;
	string  station_train_code;
	string  start_station_telecode;     //始發站
	string  start_station_name;     
	string  end_station_telecode;       //終點站
	string  end_station_name;
	string  from_station_telecode;      //出發站
	string  from_station_name;          //到達站
	string  to_station_telecode;
	string  to_station_name;
	string  start_time;
	string  arrive_time;
	string  day_difference;
	string  train_class_name;
	string  lishi;
	string  canWebBuy;
	string  lishiValue;
	string  yp_info;
	string  control_train_day;
	string  start_train_date;
	string  seat_feature;
	string  yp_ex;
	string  train_seat_feature;
	string  seat_types;
	string  location_code;
	string  from_station_no;
	string  to_station_no;
	string  control_day;
	string  sale_time;
	string  is_support_card;
	string  controlled_train_flag;
	string  controlled_train_message;
	string  train_type_code;
	string  start_province_code;
	string  start_city_code;
	string  end_province_code;
	string  end_city_code;

    string  swz_num;    //商務座	
	string  rz_num;     //軟座
    string  yz_num;     //硬座

    string  gr_num;     //高階軟臥
    string  rw_num;     //軟臥
	string  yw_num;     //硬臥

    string  tz_num;     //特等座
	string  zy_num;     //一等座
	string  ze_num;     //二等座	
    string  wz_num;     //無座

	string  gg_num;
	string  yb_num;	
	string  qt_num;
	
};

struct ticketinfo
{
	queryLeftNewDTO DTO;
	string secretStr;
	string buttonTextInfo;
};

//var station_names = '@bjb|北京北|VAP|beijingbei|bjb|0@bjd|北京東|BOP|beijingdong|bjd|1@bji|北京|BJP|beijing|bj|2
struct stationinfo
{
    string code1;
    string hanzi;
    string code2;
    string pingyin;
    string simplepingyin;
    int no;
};

struct passenager
{
    string code;  //"8"
    string passenger_name;  //"范蠡"
    string sex_code;// "M"
    string sex_name; // "男"
    string born_date; //"1989-12-08 00:00:00"
    string country_code;// "CN"
    string passenger_id_type_code;//  "1"
    string passenger_id_type_name; // "二代身份證"
    string passenger_id_no; // "14262319781108815X"
    string passenger_type; // "1"
    string passenger_flag; // "0"
    string passenger_type_name; // "成人"
    string mobile_no; // "13917043320"
    string phone_no;
    string email; // "balloonwj@qq.com"
    string address; //  ""
    string postalcode; // ""
    string first_letter;// ""
    string recordCount;// "13"
    string total_times;// "99"
    string index_id;// "0"
};

class Client12306
{
public:
    static Client12306& GetInstance();

private:
	Client12306();
	~Client12306();

private:
	Client12306(const Client12306&);
	Client12306& operator=(const Client12306&);

public:
    bool ReloadVCodeImage();

    /**
     * 遊客查票
     * https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2017-05-24&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=SHH&purpose_codes=ADULT
     * 應答:{“validateMessagesShowId”:”_validatorMessage”,”status”:true,”httpstatus”:200,”messages”:[],”validateMessages”:{}}
     *@param: train_date列車發車日期,格式:2017-01-28
     *@param: from_station出發站,格式:SHH 對應上海
     *@parma: to_station到站,格式:BJP 對應北京
     *@param: purpose_codes 票型別,成人票:ADULT 學生票:0X00
     *@param: v 查票結果
     */
    bool GuestQueryTicket(const char* train_date, const char* from_station, const char* to_station, const char* purpose_codes, vector<ticketinfo>& v);
    
    /**
	* 初始化session,獲取JSESSIONID
	*/
    bool loginInit();
	bool DownloadVCodeImage(const char* module = "login");
	/**
	*@return 0校驗成功;1校驗失敗;2校驗出錯
	*/
	int checkRandCodeAnsyn(const char* vcode);
	/**
	*@return 0校驗成功;1校驗失敗;2校驗出錯
	*/
    int loginAysnSuggest(const char* user, const char* pass, const char* vcode);

    /** 
     * 正式登入
     */
    bool userLogin();

    /** 
     * 模擬12306跳轉
     */
    bool initMy12306();

    /**
     * 拉取乘客買票驗證碼
     */
    //bool GetVCodeImage();

    /**
     * 拉取乘客買票驗證碼
     */

    /** 
     * 查詢餘票第一步
     * https://kyfw.12306.cn/otn/leftTicket/log?leftTicketDTO.train_date=2017-02-08&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=NJH&purpose_codes=ADULT
     * 應答:{“validateMessagesShowId”:”_validatorMessage”,”status”:true,”httpstatus”:200,”messages”:[],”validateMessages”:{}}
     *@param: train_date列車發車日期,格式:2017-01-28
     *@param: from_station出發站,格式:SHH 對應上海
     *@parma: to_station到站,格式:BJP 對應北京
     *@param: purpose_codes 票型別,成人票:ADULT 學生票:0X00
     */
    bool QueryTickets1(const char* train_date, const char* from_station, const char* to_station, const char* purpose_codes);

    /**
     * 查詢餘票第二步
     * 這幾種情形都有可能,所以應該都嘗試一下
     * https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2017-02-08&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=NJH&purpose_codes=ADULT
     * https://kyfw.12306.cn/otn/leftTicket/queryX?leftTicketDTO.train_date=2017-02-08&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=NJH&purpose_codes=ADULT
     * https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2017-02-08&leftTicketDTO.from_station=SHH&leftTicketDTO.to_station=NJH&purpose_codes=ADULT
     * {"status":false,"c_url":"leftTicket/query","c_name":"CLeftTicketUrl"}
     * {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"messages":["非法請求"],"validateMessages":{}}
     * 應答中含有實際餘票資訊
     *@param: train_date列車發車日期,格式:2017-01-28
     *@param: from_station出發站,格式:SHH 對應上海
     *@parma: to_station到站,格式:BJP 對應北京
     *@param: purpose_codes 票型別,成人票:ADULT 學生票:0X00
     */
    bool QueryTickets2(const char* train_date, const char* from_station, const char* to_station, const char* purpose_codes, vector<ticketinfo>& v);
    
    /** 
     * 檢測使用者是否登入
     * https://kyfw.12306.cn/otn/login/checkUser POST _json_att=
     * Cookie: JSESSIONID=0A01D967FCD9827FC664E43DEE3C7C6EF950F677C2; __NRF=86A7CBA739653C1CC2C3C3AA7C88A1E3; BIGipServerotn=1742274826.64545.0000; BIGipServerportal=3134456074.17695.0000; current_captcha_type=Z; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5357%u4EAC%2CNJH; _jc_save_fromDate=2017-01-22; _jc_save_toDate=2017-01-22; _jc_save_wfdc_flag=dc
     * {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"flag":true},"messages":[],"validateMessages":{}}
     */
    bool checkUser();

    /** 
     * 預提交訂單 POST
     * https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest?secretStr=secretStr&train_date=2017-01-21&back_train_date=2016-12-23&tour_flag=dc&purpose_codes=ADULT&query_from_station_name=深圳&query_to_station_name=武漢&undefined=
     */
    bool submitOrderRequest(const char* secretStr, const char* train_date, const char* back_train_date, const char* tour_flag, const char* purpose_codes, const char* query_from_station_name, const char* query_to_station_name);

    /** 
     * 模擬跳轉頁面InitDc,Post
     */
    bool initDc();

    /**
     * 拉取常用聯絡人 POST
     * https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs?_json_att=&REPEAT_SUBMIT_TOKEN=SubmitToken
     */
    bool getPassengerDTOs(vector<passenager>& v);

    /** 
     * 購票人確定
     * https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo
     @param oldPassengerStr	oldPassengerStr組成的格式:乘客名,passenger_id_type_code,passenger_id_no,passenger_type,’_’
                            示例: 范蠡,1,14262319781108815X,1_
     @param passengerTicketStr	passengerTicketStr組成的格式:seatType,0,票型別(成人票填1),乘客名,passenger_id_type_code,passenger_id_no,mobile_no,’N’ 
                            示例: O,0,1,范蠡,1,14262319781108815X,13917043320,N	101
     @tour_flag	dc表示單程票
     應答:{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"ifShowPassCode":"N","canChooseBeds":"N","canChooseSeats":"N","choose_Seats":"MOP9","isCanChooseMid":"N","ifShowPassCodeTime":"1","submitStatus":true,"smokeStr":""},"messages":[],"validateMessages":{}}
     */
    bool checkOrderInfo(const char* oldPassengerStr, const char* passengerTicketStr, const char* tour_flag, bool& bVerifyVCode);

    /** 
     * 準備進入排隊
     * https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount
     _json_att		10
     fromStationTelecode	VNP	23
     leftTicket	enu80ehMzuVJlK2Q43c6kn5%2BzQF41LEI6Nr14JuzThrooN57	63
     purpose_codes	00	16
     REPEAT_SUBMIT_TOKEN	691c09b5605e46bfb2ec2380ee65de0e	52
     seatType	O	10
     stationTrainCode	G5	19
     toStationTelecode	AOH	21
     train_date	Fri Feb 10 00:00:00 UTC+0800 2017	50
     train_location	P2	17
     train_no	24000000G502	21
     應答:{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"count":"4","ticket":"669","op_2":"false","countT":"0","op_1":"true"},"messages":[],"validateMessages":{}}
     */
    bool getQueueCount(const char* fromStationTelecode, const char* leftTicket, const char* purpose_codes, const char* seatType, const char* stationTrainCode, const char* toStationTelecode, const char* train_date, const char* train_location, const char* train_no);

    /** 
     * 確認購買
     * https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue
     _json_att		10
     choose_seats		13
     dwAll	N	7
     key_check_isChange	7503FD317E01E290C3D95CAA1D26DD8CFA9470C3643BA9799D3FB753	75
     leftTicketStr	enu80ehMzuVJlK2Q43c6kn5%2BzQF41LEI6Nr14JuzThrooN57	66
     oldPassengerStr	范蠡,1,14262319781108815X,1_	73
     passengerTicketStr	O,0,1,范蠡,1,14262319781108815X,13917043320,N	101
     purpose_codes	00	16
     randCode		9
     REPEAT_SUBMIT_TOKEN	691c09b5605e46bfb2ec2380ee65de0e	52
     roomType	00	11
     seatDetailType	000	18
     train_location	P2	17
     應答:{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"submitStatus":true},"messages":[],"validateMessages":{}}
     */
    bool confirmSingleForQueue(const char* leftTicketStr, const char* oldPassengerStr, const char* passengerTicketStr, const char* purpose_codes, const char* train_location);

    /** 
     * 查詢訂單狀態: https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random=1486368851278&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=691c09b5605e46bfb2ec2380ee65de0e
     GET
     _json_att
     random	1486368851278
     REPEAT_SUBMIT_TOKEN	691c09b5605e46bfb2ec2380ee65de0e
     tourFlag	dc
     響應:{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"queryOrderWaitTimeStatus":true,"count":0,"waitTime":-1,"requestId":6234282826330508533,"waitCount":0,"tourFlag":"dc","orderId":"E061149209"},"messages":[],"validateMessages":{}}
     */
    bool queryOrderWaitTime(const char* tourflag, string& orderId);

    /** 
     * https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue POST
     _json_att		10
     orderSequence_no	E061149209	27
     REPEAT_SUBMIT_TOKEN	691c09b5605e46bfb2ec2380ee65de0e	52
     {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"submitStatus":true},"messages":[],"validateMessages":{}}
     */
    //bool resultOrderForDcQueue();

    /** 
     * 未完成的訂單頁面 https://kyfw.12306.cn/otn/queryOrder/initNoComplete GET
     * 獲取未完成的訂單 https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete POST _json_att=
     */
    /*
    {
    "validateMessagesShowId": "_validatorMessage",
    "status": true,
    "httpstatus": 200,
    "data": {
        "orderDBList": [
            {
                "sequence_no": "E079331507",
                "order_date": "2017-02-09 10:10:55",
                "ticket_totalnum": 1,
                "ticket_price_all": 55300,
                "cancel_flag": "Y",
                "resign_flag": "4",
                "return_flag": "N",
                "print_eticket_flag": "N",
                "pay_flag": "Y",
                "pay_resign_flag": "N",
                "confirm_flag": "N",
                "tickets": [
                    {
                        "stationTrainDTO": {
                            "trainDTO": {},
                            "station_train_code": "G41",
                            "from_station_telecode": "VNP",
                            "from_station_name": "北京南",
                            "start_time": "1970-01-01 09:16:00",
                            "to_station_telecode": "AOH",
                            "to_station_name": "上海虹橋",
                            "arrive_time": "1970-01-01 14:48:00",
                            "distance": "1318"
                        },
                        "passengerDTO": {
                            "passenger_name": "范蠡",
                            "passenger_id_type_code": "1",
                            "passenger_id_type_name": "二代身份證",
                            "passenger_id_no": "14262319781108815X",
                            "total_times": "98"
                        },
                        "ticket_no": "E079331507110008B",
                        "sequence_no": "E079331507",
                        "batch_no": "1",
                        "train_date": "2017-02-11 00:00:00",
                        "coach_no": "10",
                        "coach_name": "10",
                        "seat_no": "008B",
                        "seat_name": "08B號",
                        "seat_flag": "0",
                        "seat_type_code": "O",
                        "seat_type_name": "二等座",
                        "ticket_type_code": "1",
                        "ticket_type_name": "成人票",
                        "reserve_time": "2017-02-09 10:10:55",
                        "limit_time": "2017-02-09 10:10:55",
                        "lose_time": "2017-02-09 10:40:55",
                        "pay_limit_time": "2017-02-09 10:40:55",
                        "ticket_price": 55300,
                        "print_eticket_flag": "N",
                        "resign_flag": "4",
                        "return_flag": "N",
                        "confirm_flag": "N",
                        "pay_mode_code": "Y",
                        "ticket_status_code": "i",
                        "ticket_status_name": "待支付",
                        "cancel_flag": "Y",
                        "amount_char": 0,
                        "trade_mode": "",
                        "start_train_date_page": "2017-02-11 09:16",
                        "str_ticket_price_page": "553.0",
                        "come_go_traveller_ticket_page": "N",
                        "return_deliver_flag": "N",
                        "deliver_fee_char": "",
                        "is_need_alert_flag": false,
                        "is_deliver": "N",
                        "dynamicProp": "",
                        "fee_char": "",
                        "insure_query_no": ""
                    }
                ],
                "reserve_flag_query": "p",
                "if_show_resigning_info": "N",
                "recordCount": "1",
                "isNeedSendMailAndMsg": "N",
                "array_passser_name_page": [
                    "范蠡"
                ],
                "from_station_name_page": [
                    "北京南"
                ],
                "to_station_name_page": [
                    "上海虹橋"
                ],
                "start_train_date_page": "2017-02-11 09:16",
                "start_time_page": "09:16",
                "arrive_time_page": "14:48",
                "train_code_page": "G41",
                "ticket_total_price_page": "553.0",
                "come_go_traveller_order_page": "N",
                "canOffLinePay": "N",
                "if_deliver": "N",
                "insure_query_no": ""
            }
        ],
        "to_page": "db"
    },
    "messages": [],
    "validateMessages": {}
}
    */

    /** 
     * 已完成訂單(改/退) : https://kyfw.12306.cn/otn/queryOrder/queryMyOrder POST
     * queryType 1 按訂票日期 2 按乘車日期
     * 查詢日期queryStartDate=2017-02-09&queryEndDate=2017-02-09
     * come_from_flag: my_order 全部 my_resign 可改簽 my_cs_resign 可變更到站 my_refund 可退票
     * &pageSize=8&pageIndex=0&
     * query_where G 未出行訂單 H 歷史訂單
     * sequeue_train_name 訂單號/車次/乘客姓名
     */
    /* 歷史訂單格式
       參見[歷史訂單.txt]
    */
    
    /** 
     * 獲取全國車站資訊
     *@param si 返回的車站資訊
     *@param bForceDownload 強制從網路上下載,即不使用本地副本
     */
    bool GetStationInfo(vector<stationinfo>& si, bool bForceDownload = false);

    /** 
     * 獲取所有高校資訊 https://kyfw.12306.cn/otn/userCommon/schoolNames POST provinceCode=11&_json_att=
     */

    /** 
     * 獲取所有城市資訊 https://kyfw.12306.cn/otn/userCommon/allCitys POST station_name=&_json_att=
     */

	/**
	 * 查詢常用聯絡人
	 */
	bool QueryPassengers(int pageindex = 2, int pagesize = 10);


    bool GetVCodeFileName(char* pszDst, int nLength);

private:
    bool GetCookies(const string& data);

    /**
     * 傳送一個http請求
     *@param url 請求的url
     *@param strResponse http響應結果
     *@param get true為GET,false為POST
     *@param headers 附帶傳送的http頭資訊
     *@param postdata post附帶的資料    
     *@param bReserveHeaders http響應結果是否保留頭部資訊
     *@param timeout http請求超時時間
     */
    bool HttpRequest(const char* url, string& strResponse, bool get = true, const char* headers = NULL, const char* postdata = NULL, bool bReserveHeaders = false, int timeout = 10);

private:
    char                m_szCurrVCodeName[256]; //當前驗證碼圖片的名稱
    string              m_strCookies;
    string              m_strGlobalRepeatSubmitToken;
    string              m_strKeyCheckIsChange;
};


#endif //!__CLIENT_12306_H__
複製程式碼

完整原始碼下載

具體的實現程式碼就不在文章中貼出來了,您可以下載我的程式碼。下載地址在微信公眾號『easyserverdev』中回覆『12306原始碼』即可得到下載地址,當然,由於12306的介面經常發生改變,當你拿到程式碼時,可能12306伺服器的介面已經稍微發生了改變,您可以按上面介紹的原理做相應的修改。

最後當您實現了基本的登入和購票功能後,你就可以不斷模擬某些請求去進行刷票了。

文章版權所有,轉載請保留版權申明。

歡迎關注公眾號『easyserverdev』。如果有任何技術或者職業方面的問題需要我提供幫助,可通過這個公眾號與我取得聯絡,此公眾號不僅分享高效能伺服器開發經驗和故事,同時也免費為廣大技術朋友提供技術答疑和職業解惑,您有任何問題都可以在微信公眾號直接留言,我會盡快回復您。

從零實現一款12306搶票軟體

相關文章