zoukankan      html  css  js  c++  java
  • GET请求12306网站链接获取火车站代号信息更新到后台数据库表中

    之前写过“使用HTTP GET请求12306网站接口获取车站名和车站Code”。链接地址是:

       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; }
            }
        }
    }
    Station站点信息Model类

     其次,用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()
            {
                string formUrl = "http://dynamic.12306.cn/otsweb/js/common/station_name.js";
    
                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('@');
    
                        foreach (var station in stations)
                        {
                            if (string.IsNullOrEmpty(station))
                            {
                                continue;
                            }
    
                            string[] names = station.Split('|');
    
                            list.Add(new Station()
                            {
                                Shorthand = names[0],
                                Name = names[1],
                                Code = names[2],
                                Pinyin = names[3],
                                FirstLetter = names[4],
                                Order = names[5]
                            });
                        }
                    }
                }
    
                catch (Exception)
                {
    
                }
                SendSMSResponse.Close();
                SendSMSResponseStream.Close();
                return list;
            }
    

    再次,连接MySql数据库,写一个insert方法,将上述缓存取得的数据更新到数据库表中。

            /// <summary>
            /// 向data_jtfw_hc_code表中插入数据
            /// </summary>
            /// <param name="t_name"></param>
            /// <param name="t_code"></param>
            public static void InsertData(string t_name, string t_code)
            {
                using (MySqlConnection conn = new MySqlConnection(MySqlString))
                {
                    string mysql = string.Format("insert into data_jtfw_hc_code(name,code) values ('{0}','{1}')", t_name, t_code);
                    MySqlCommand cmd = new MySqlCommand(mysql, conn);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    conn.Dispose();
                }
            }
    

    最后,调用获取站点信息方法和更新数据库表数据方法,获取处理过的信息已经存在了list集合中,通过实例化Model类,根据name,code字段遍历出数据,往数据库中更新。。。在Main()方法中调用的代码示例如下:

           static void Main(string[] args)
            {
                List<Station> lst = new List<Station>();
                lst = GetStations();
                foreach (Station st in lst)
                {
                    InsertData(st.Name, st.Code);
                }
                Console.WriteLine("已执行完毕!!!");
                Console.Read();
            }

    点击执行,所有获取的信息就这样轻而易举的更新到了数据库。。。

    以上也算是完整的代码示例了,如果您想要源码,请触击以下链接,然后输入访问密码(访问密码:83f2):

       http://yunpan.cn/QegWkHcdegSF4  

    一家之言,仅供参考!!!

  • 相关阅读:
    java实现第四届蓝桥杯连续奇数和
    java实现第四届蓝桥杯连续奇数和
    java实现第四届蓝桥杯连续奇数和
    java实现第四届蓝桥杯连续奇数和
    java实现第四届蓝桥杯连续奇数和
    java实现第四届蓝桥杯猜灯谜
    Idea开发环境中搭建Maven并且使用Maven打包部署程序
    IntelliJ IDEA最新版配置Tomcat(完整版教程)
    ActiveMQ安装部署(Windows)
    个人龙果支付系统的部署及运行
  • 原文地址:https://www.cnblogs.com/litao4047/p/3115616.html
Copyright © 2011-2022 走看看