GET請求12306網站連結獲取火車站代號資訊更新到後臺資料庫表中
http://www.cnblogs.com/litao4047/archive/2013/05/31/3110781.html
這個連結所表述的內容是,從12306網站上利用get解析地址獲取車站名和代號,獲取到的資料就是網站上的那個js檔案(資料沒有經過處理),全國火車站代號字典:station_name.js。
今天,所要講述的就是,處理上面連結獲取到的資料,寫個插入方法將資料更新到資料庫表中。處理獲取到的資料形式如下:
比如,獲取的一條資料是var
station_names =
'@bjb|北京北|VAP|beijingbei|bjb|0'
;經過處理後(欄位分割),想要是資料就是'北京北'和'VAP',然後將這樣的資料更新到後臺資料庫中。
首先,將形如'@bjb|北京北|VAP|beijingbei|bjb|0'的資料分割成六個欄位firstLetter(首字母),name(站點名),code(站點代號),pinyin(全拼),shorthand(縮寫),order(排序),建立一個Model類用於儲存資料,程式碼示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Update_Train_Code { /// <summary> /// 站點資訊/// </summary> public class Station { private string name;//站點名 public string Name { get { return name; } set { name = value; } } private string code;//縮寫 public string Code { get { return code; }set { code = value; } } private string firstLetter;//首字母 public string FirstLetter { get { return firstLetter; } set { firstLetter = value; } } private string pinyin;// 全拼 public string Pinyin { get { return pinyin; } set { pinyin = value; } } private string shorthand;// 簡寫 public string Shorthand { get { return shorthand; } set { shorthand = value; } } private string order;// 排序 public string Order { get { return order; } set { order = value; } } } }
其次,用get請求http://dynamic.12306.cn/otsweb/js/common/station_name.js地址解析資料,將得到的資料進行快取,欄位分割處理儲存於List<Station>泛型集合中,返回list。
///
<summary>
///
獲取車站資訊
///
</summary>
///
<param name="timeout"></param>
///
<param name="userAgent"></param>
///
<param name="cookie"></param>
public static List<Station>
GetStations()
{
CookieContainer
cookieContainer = new CookieContainer();
HttpWebRequest
request = WebRequest.Create(formUrl) as HttpWebRequest;
request.Method
= "GET" ;
request.KeepAlive
= false ;
request.AllowAutoRedirect
= true ;
request.ContentType
= "application/x-www-form-urlencoded" ;
request.UserAgent
= "Mozilla/4.0
(compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" ;
request.CookieContainer
= cookieContainer;
HttpWebResponse
SendSMSResponse = (HttpWebResponse)request.GetResponse();
StreamReader
SendSMSResponseStream = new StreamReader(SendSMSResponse.GetResponseStream());
string response
= SendSMSResponseStream.ReadToEnd();
List<Station>
list = new List<Station>();
try
{
var str
= response;
Regex
stationNamesRegex = new Regex( "'(?<stationNames>[^\']*?)'" );
if (stationNamesRegex.IsMatch(str))
{
string stationNames
= stationNamesRegex.Matches(str)[0].Groups[ "stationNames" ].Value;
string []
stations = stationNames.Split(
|