亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

從零實現一款12306搶票軟件

發布時間:2020-04-05 09:52:15 來源:網絡 閱讀:3967 作者:張小方32 欄目:建站服務器

寫在前面的話

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

關于http請求的格式和如何組裝http數據包給服務器發送請求,我們在上一篇文章《從零實現一個http服務器》中已經詳細介紹過了,如果還不明白的朋友可以去那篇文章看下。

鄭重申明一下:這里介紹的技術僅供用于學習,不可用于惡意×××12306服務器,請勿濫用本文介紹的技術。對12306服務器造成的任何損失,后果自負。

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

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

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

2、一個可以登錄12306網址并且可以購票的12306賬號

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

一、查票與站點信息接口

之所以先分析這個接口,是因為查票不需要用戶登錄的,相對來說最簡單。我們在Chrome瀏覽器中打開12306余票查詢頁面,網址是:https://kyfw.12306.cn/otn/leftTicket/init,如下圖所示:

從零實現一款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|HVY2cA5DQzMC1VDiotEG4zXAOwG4fHHYq2bh2ZFhm47pySly|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/T247JdvbJCFWkXvFimDh5W5rNAht1O5/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/YLarh7s3|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服務器》我們知道這是一個http GET請求,其中在url后面是請求附帶的參數:

leftTicketDTO.train_date: 2018-05-20
leftTicketDTO.from_station: SHH
leftTicketDTO.to_station: BJP
purpose_codes: ADULT

這四個參數分別是購票日期、出發站、到達站和票類型(這里是成人票(普通票)),正好對應我們界面上的查詢信息:

從零實現一款12306搶票軟件

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

從零實現一款12306搶票軟件

進入查票頁面之前,瀏覽器從https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9053下載一個叫station.name.js文件,這是一個javascript腳本,里面只有一行代碼,就是定義了一個station_names的js變量,之所以url地址后面加一個station_version=1.9053,你可以理解成版本號,但是主要是通過一個隨機值1.9053,讓瀏覽器不要使用緩存中的station_name.js,而是每次都從服務器重新加載下這個文件,這樣的話如果站點信息有更新,也可以避免因為緩存問題,導致本地的緩存與服務器上的站點信息不一致。由于站點信息比較多,我們截個圖吧:

從零實現一款12306搶票軟件

看上圖,我們可以看出來,每個站點信息都是通過@符號分割,然后通過|分割每一個站點的各種信息。這樣的話,根據上文的格式假如我們要查詢2018年5月30日從長春到南京的火車普通票,就可以通過網址https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2018-05-30&leftTicketDTO.from_station=CCT&leftTicketDTO.to_station=NJH&purpose_codes=ADULT。

當然,這里需要說明一下的就是,由于全國的火車站點信息文件比較大,我們程序解析起來時間較長,加上火車站編碼信息并不是經常變動,所以,我們我們沒必要每次都下載這個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的登錄界面:https://kyfw.12306.cn/otn/login/init,如下圖所示:

從零實現一款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;
}

我們再看下驗證碼去服務器驗證的接口https://kyfw.12306.cn/passport/captcha/captcha-check。

請求頭:


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服務器》也詳細做了介紹,還不清楚的可以參見上一篇文章。所以對于向圖片驗證碼坐標信息中含有的逗號信息就要進行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搶票軟件

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

鄱阳县| 临沧市| 汉川市| 日照市| 临澧县| 武定县| 长岛县| 大同市| 绵竹市| 安图县| 秦安县| 咸宁市| 葵青区| 闵行区| 永胜县| 龙江县| 淮滨县| 商洛市| 南汇区| 青州市| 兴山县| 台前县| 惠州市| 通城县| 荆门市| 肥城市| 无棣县| 蓬莱市| 萍乡市| 长宁区| 晋中市| 石河子市| 芒康县| 永昌县| 淮安市| 乌拉特前旗| 邵阳市| 北辰区| 双桥区| 松江区| 华蓥市|