编程乐趣:C#实现12306自动登录(2013年11月27)

依然使用IE9的捕获参数,做了一个12306的登录功能。参照了网上童鞋们的做法。
其他都和前面几篇读取余票、票价一样,不过登录要用到证书的问题,这个参考了一个网上的例子。
不过12306会随时变化,下面的登录不一定一直都能成功。如果12306有变化,大家可以根据变化对代码做修改。总之使用的方法不变,就是捕获参数和url,然后自己补充参数。
效果如下:

项目名称:Test12306AutoLogin;
环境:.net 4.0,Visual studio 2010;
项目图:

直接贴代码了。
核心代码如下,
信任证书代码:
[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Messenger  
  2.    {  
  3.        public Messenger()  
  4.        {  
  5.        }  
  6.   
  7.   
  8.        public void Register(string message, Action callback)  
  9.        {  
  10.            this.Register(message, callback, null);  
  11.        }  
  12.   
  13.   
  14.        public void Register<T>(string message, Action<T> callback)  
  15.        {  
  16.            this.Register(message, callback, typeof(T));  
  17.        }  
  18.   
  19.   
  20.        void Register(string message, Delegate callback, Type parameterType)  
  21.        {  
  22.            if (String.IsNullOrEmpty(message))  
  23.                throw new ArgumentException("'message' cannot be null or empty.");  
  24.   
  25.   
  26.            if (callback == null)  
  27.                throw new ArgumentNullException("callback");  
  28.   
  29.   
  30.            this.VerifyParameterType(message, parameterType);  
  31.   
  32.   
  33.            _messageToActionsMap.AddAction(message, callback.Target, callback.Method, parameterType);  
  34.        }  
  35.   
  36.   
  37.        [Conditional("DEBUG")]  
  38.        void VerifyParameterType(string message, Type parameterType)  
  39.        {  
  40.            Type previouslyRegisteredParameterType = null;  
  41.            if (_messageToActionsMap.TryGetParameterType(message, out previouslyRegisteredParameterType))  
  42.            {  
  43.                if (previouslyRegisteredParameterType != null && parameterType != null)  
  44.                {  
  45.                    if (!previouslyRegisteredParameterType.Equals(parameterType))  
  46.                        throw new InvalidOperationException(string.Format(  
  47.                            "The registered action's parameter type is inconsistent with the previously registered actions for message '{0}'.\nExpected: {1}\nAdding: {2}",  
  48.                            message,   
  49.                            previouslyRegisteredParameterType.FullName,  
  50.                            parameterType.FullName));  
  51.                }  
  52.                else  
  53.                {  
  54.                    // One, or both, of previouslyRegisteredParameterType or callbackParameterType are null.  
  55.                    if (previouslyRegisteredParameterType != parameterType)   // not both null?  
  56.                    {  
  57.                        throw new TargetParameterCountException(string.Format(  
  58.                            "The registered action has a number of parameters inconsistent with the previously registered actions for message \"{0}\".\nExpected: {1}\nAdding: {2}",  
  59.                            message,  
  60.                            previouslyRegisteredParameterType == null ? 0 : 1,  
  61.                            parameterType == null ? 0 : 1));  
  62.                    }  
  63.                }  
  64.            }  
  65.        }  
  66.   
  67.   
  68.        public void NotifyColleagues(string message, object parameter)  
  69.        {  
  70.            if (String.IsNullOrEmpty(message))  
  71.                throw new ArgumentException("'message' cannot be null or empty.");  
  72.   
  73.   
  74.            Type registeredParameterType;  
  75.            if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType))  
  76.            {  
  77.                if (registeredParameterType == null)  
  78.                    throw new TargetParameterCountException(string.Format("Cannot pass a parameter with message '{0}'. Registered action(s) expect no parameter.", message));  
  79.            }  
  80.   
  81.   
  82.            var actions = _messageToActionsMap.GetActions(message);  
  83.            if (actions != null)  
  84.                actions.ForEach(action => action.DynamicInvoke(parameter));  
  85.        }  
  86.   
  87.   
  88.        public void NotifyColleagues(string message)  
  89.        {  
  90.            if (String.IsNullOrEmpty(message))  
  91.                throw new ArgumentException("'message' cannot be null or empty.");  
  92.   
  93.   
  94.            Type registeredParameterType;  
  95.            if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType))  
  96.            {  
  97.                if (registeredParameterType != null)  
  98.                    throw new TargetParameterCountException(string.Format("Must pass a parameter of type {0} with this message. Registered action(s) expect it.", registeredParameterType.FullName));  
  99.            }  
  100.   
  101.   
  102.            var actions = _messageToActionsMap.GetActions(message);  
  103.            if (actions != null)  
  104.                actions.ForEach(action => action.DynamicInvoke());  
  105.        }  
  106.   
  107.   
  108.        
  109.        private class MessageToActionsMap  
  110.        {  
  111.            internal MessageToActionsMap()  
  112.            {  
  113.            }  
  114.   
  115.   
  116.             
  117.            internal void AddAction(string message, object target, MethodInfo method, Type actionType)  
  118.            {  
  119.                if (message == null)  
  120.                    throw new ArgumentNullException("message");  
  121.   
  122.   
  123.                if (method == null)  
  124.                    throw new ArgumentNullException("method");  
  125.   
  126.   
  127.                lock (_map)  
  128.                {  
  129.                    if (!_map.ContainsKey(message))  
  130.                        _map[message] = new List<WeakAction>();  
  131.   
  132.   
  133.                    _map[message].Add(new WeakAction(target, method, actionType));  
  134.                }  
  135.            }  
  136.   
  137.   
  138.            internal List<Delegate> GetActions(string message)  
  139.            {  
  140.                if (message == null)  
  141.                    throw new ArgumentNullException("message");  
  142.   
  143.   
  144.                List<Delegate> actions;  
  145.                lock (_map)  
  146.                {  
  147.                    if (!_map.ContainsKey(message))  
  148.                        return null;  
  149.   
  150.   
  151.                    List<WeakAction> weakActions = _map[message];  
  152.                    actions = new List<Delegate>(weakActions.Count);  
  153.                    for (int i = weakActions.Count - 1; i > -1; --i)  
  154.                    {  
  155.                        WeakAction weakAction = weakActions[i];  
  156.                        if (weakAction == null)  
  157.                            continue;  
  158.   
  159.   
  160.                        Delegate action = weakAction.CreateAction();  
  161.                        if (action != null)  
  162.                        {  
  163.                            actions.Add(action);  
  164.                        }  
  165.                        else  
  166.                        {  
  167.                            // The target object is dead, so get rid of the weak action.  
  168.                            weakActions.Remove(weakAction);  
  169.                        }  
  170.                    }  
  171.   
  172.   
  173.                    // Delete the list from the map if it is now empty.  
  174.                    if (weakActions.Count == 0)  
  175.                        _map.Remove(message);  
  176.                }  
  177.   
  178.   
  179.                // Reverse the list to ensure the callbacks are invoked in the order they were registered.  
  180.                actions.Reverse();  
  181.   
  182.   
  183.                return actions;  
  184.            }  
  185.   
  186.   
  187.            internal bool TryGetParameterType(string message, out Type parameterType)  
  188.            {  
  189.                if (message == null)  
  190.                    throw new ArgumentNullException("message");  
  191.   
  192.   
  193.                parameterType = null;  
  194.                List<WeakAction> weakActions;  
  195.                lock (_map)  
  196.                {  
  197.                    if (!_map.TryGetValue(message, out weakActions) || weakActions.Count == 0)  
  198.                        return false;  
  199.                }  
  200.                parameterType = weakActions[0].ParameterType;  
  201.                return true;  
  202.            }  
  203.   
  204.   
  205.            readonly Dictionary<string, List<WeakAction>> _map = new Dictionary<string, List<WeakAction>>();  
  206.        }  
  207.   
  208.   
  209.       
  210.        private class WeakAction  
  211.        {  
  212.             
  213.            internal WeakAction(object target, MethodInfo method, Type parameterType)  
  214.            {  
  215.                if (target == null)  
  216.                {  
  217.                    _targetRef = null;  
  218.                }  
  219.                else  
  220.                {  
  221.                    _targetRef = new WeakReference(target);  
  222.                }  
  223.   
  224.   
  225.                _method = method;  
  226.   
  227.   
  228.                this.ParameterType = parameterType;  
  229.   
  230.   
  231.                if (parameterType == null)  
  232.                {  
  233.                    _delegateType = typeof(Action);  
  234.                }  
  235.                else  
  236.                {  
  237.                    _delegateType = typeof(Action<>).MakeGenericType(parameterType);  
  238.                }  
  239.            }  
  240.   
  241.   
  242.            internal Delegate CreateAction()  
  243.            {  
  244.                // Rehydrate into a real Action object, so that the method can be invoked.  
  245.                if (_targetRef == null)  
  246.                {  
  247.                    return Delegate.CreateDelegate(_delegateType, _method);  
  248.                }  
  249.                else  
  250.                {  
  251.                    try  
  252.                    {  
  253.                        object target = _targetRef.Target;  
  254.                        if (target != null)  
  255.                            return Delegate.CreateDelegate(_delegateType, target, _method);  
  256.                    }  
  257.                    catch  
  258.                    {  
  259.                    }  
  260.                }  
  261.   
  262.   
  263.                return null;  
  264.            }  
  265.   
  266.   
  267.            internal readonly Type ParameterType;  
  268.            readonly Type _delegateType;  
  269.            readonly MethodInfo _method;  
  270.            readonly WeakReference _targetRef;  
  271.        }  
  272.   
  273.   
  274.        readonly MessageToActionsMap _messageToActionsMap = new MessageToActionsMap();  
  275.    }  
登录的所有方法类:

[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Login12306Manager  
  2.     {  
  3.         private static readonly Messenger s_messenger = new Messenger();  
  4.   
  5.   
  6.         public static Messenger SMessenger { get { return s_messenger; } }  
  7.   
  8.   
  9.         public const string APPEND_MESSAGE = "append_message";  
  10.   
  11.   
  12.         public static string afterLoginCookie;  
  13.   
  14.   
  15.         private static string beforLoginCookie;  
  16.   
  17.   
  18.         static Login12306Manager()  
  19.         {  
  20.             SetCertificatePolicy();  
  21.         }  
  22.   
  23.   
  24.         /// <summary>  
  25.         /// 登 录  
  26.         /// </summary>  
  27.         public static string Login(string userName,string password, string randomCode)  
  28.         {  
  29.             string resultHtml = string.Empty;  
  30.   
  31.   
  32.             try  
  33.             {  
  34.                 string loginRand= DoGetLoginRand();  
  35.   
  36.   
  37.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create  
  38.                     (@"https://dynamic.12306.cn/otsweb/loginAction.do?method=login");  
  39.   
  40.   
  41.                 request.Accept = @"text/html, application/xhtml+xml, */*";  
  42.   
  43.   
  44.                 request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";  
  45.   
  46.   
  47.                 request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";  
  48.   
  49.   
  50.                 request.ContentType = @"application/x-www-form-urlencoded";  
  51.   
  52.   
  53.                 request.Headers[HttpRequestHeader.Cookie] = beforLoginCookie;  
  54.   
  55.   
  56.                 request.Method = "POST";  
  57.   
  58.   
  59.                 byte[] buffer = new byte[0];  
  60.                 string parameter =  
  61. @"loginRand={0}&refundLogin=N&refundFlag=Y&isClick=&form_tk=null&loginUser.user_name={1}&nameErrorFocus=&user.password={2}&passwordErrorFocus=&randCode={3}&randErrorFocus=&NDU0NzY4NA%3D%3D=Nzg4ZDAxMGNkYTZlMTRjZA%3D%3D&myversion=undefined";  
  62.   
  63.   
  64.                 parameter = string.Format(parameter, loginRand, userName, password, randomCode);  
  65.   
  66.   
  67.                 buffer = Encoding.UTF8.GetBytes(parameter);  
  68.   
  69.   
  70.                 request.ContentLength = buffer.Length;  
  71.                 using (Stream writer = request.GetRequestStream())  
  72.                 {  
  73.                     writer.Write(buffer, 0, buffer.Length);  
  74.   
  75.   
  76.                     writer.Flush();  
  77.                 }  
  78.   
  79.   
  80.                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
  81.                 {  
  82.                     afterLoginCookie = response.GetResponseHeader("Set-cookie");  
  83.   
  84.   
  85.                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
  86.                     {  
  87.                         resultHtml = reader.ReadToEnd();  
  88.   
  89.   
  90.                         resultHtml = ProcessLoginResult(resultHtml);  
  91.                     }  
  92.                 }  
  93.             }  
  94.             catch{ }  
  95.   
  96.   
  97.             return resultHtml;  
  98.         }  
  99.   
  100.   
  101.   
  102.   
  103.         /// <summary>  
  104.         /// 刷新验证码  
  105.         /// </summary>  
  106.         public static string RefreshCode()  
  107.         {  
  108.             string randImageUrl = string.Empty;  
  109.   
  110.   
  111.             try  
  112.             {  
  113.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(@"https://dynamic.12306.cn/otsweb/passCodeNewAction.do?module=login&rand=sjrand&{0}",  
  114.   
  115.   
  116.                     new Random().Next(10000, 1000000)));  
  117.   
  118.   
  119.                 request.Accept = @"image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";  
  120.   
  121.   
  122.                 request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";  
  123.   
  124.   
  125.                 request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";  
  126.   
  127.   
  128.                 request.Method = "GET";  
  129.   
  130.   
  131.                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
  132.                 {  
  133.                     beforLoginCookie = response.GetResponseHeader("Set-cookie");  
  134.   
  135.   
  136.                     beforLoginCookie = Regex.Replace(beforLoginCookie, "path(?:[^,]+),?""", RegexOptions.IgnoreCase);  
  137.   
  138.   
  139.                     using (Stream reader = response.GetResponseStream())  
  140.                     {  
  141.                         string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, new Random().Next(10000, 99999) + @"loginRandCode.JPEG");  
  142.   
  143.   
  144.                         using (FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))  
  145.                         {  
  146.                             reader.CopyTo(file);  
  147.                         }  
  148.   
  149.   
  150.                         randImageUrl = path;  
  151.                     }  
  152.                 }  
  153.             }  
  154.             catch { }  
  155.   
  156.   
  157.             return randImageUrl;  
  158.         }  
  159.   
  160.   
  161.         private static string DoGetLoginRand()  
  162.         {  
  163.             string loginRand=string.Empty;  
  164.   
  165.   
  166.             try  
  167.             {  
  168.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://dynamic.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest");  
  169.   
  170.   
  171.                 request.Accept = @"application/json, text/javascript, */*";  
  172.   
  173.   
  174.                 request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";  
  175.   
  176.   
  177.                 request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";  
  178.   
  179.   
  180.                 request.Headers[HttpRequestHeader.Cookie] = beforLoginCookie;  
  181.   
  182.   
  183.                 request.Method = "POST";  
  184.   
  185.   
  186.                 byte[] buffer = new byte[0];  
  187.   
  188.   
  189.                 buffer = Encoding.UTF8.GetBytes(string.Empty);  
  190.   
  191.   
  192.                 request.ContentLength = buffer.Length;  
  193.   
  194.   
  195.                 using (Stream writer = request.GetRequestStream())  
  196.                 {  
  197.                     writer.Write(buffer, 0, buffer.Length);  
  198.   
  199.   
  200.                     writer.Flush();  
  201.                 }  
  202.   
  203.   
  204.                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
  205.                 {  
  206.                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
  207.                     {  
  208.                         string result = reader.ReadToEnd();  
  209.   
  210.   
  211.                         var loginRandContent = JsonConvert.DeserializeObject<BeforLoginRnad>(result);  
  212.   
  213.   
  214.                         loginRand = loginRandContent.loginRand;  
  215.                     }  
  216.                 }  
  217.             }  
  218.             catch {}  
  219.   
  220.   
  221.             return loginRand;  
  222.         }  
  223.   
  224.   
  225.         /// <summary>  
  226.         /// 处理登录结果  
  227.         /// </summary>  
  228.         /// <param name="html">登录后返回的html文本</param>  
  229.         private static string ProcessLoginResult(string html)  
  230.         {  
  231.             string m_msgPattern = "message[^\"]+\"(?'message'[^\"]+)\";";  
  232.   
  233.   
  234.             string m_isLoginPatter = "isLogin\\s*=\\s*(?<val>.+)\n";  
  235.   
  236.   
  237.             string m_loginUserNamePattern = "u_name\\s*=\\s*['\"](?<name>.+)['\"]";  
  238.   
  239.   
  240.             if (html.Contains("请输入正确的验证码"))  
  241.             {  
  242.                 return "验证码错误";  
  243.             }  
  244.             else if (html.Contains("当前访问用户过多"))  
  245.             {  
  246.                 return "当前访问用户过多,请稍后再试...";  
  247.             }  
  248.             else  
  249.             {  
  250.                 var match0 = Regex.Match(html, m_msgPattern, RegexOptions.Compiled);  
  251.   
  252.   
  253.                 if (match0.Success)  
  254.                 {  
  255.                     string text = match0.Groups["message"].Value;  
  256.   
  257.   
  258.                     if (text.Contains("密码") || text.Contains("登录名不存在"))  
  259.                     {  
  260.                         return "用户名或者密码错误";  
  261.                     }  
  262.                     else  
  263.                     {  
  264.                       return text;  
  265.                     }  
  266.                 }  
  267.   
  268.   
  269.   
  270.   
  271.                 var match = Regex.Match(html, m_isLoginPatter, RegexOptions.Compiled);  
  272.   
  273.   
  274.                 if (match.Success && (match.Groups["val"].Value.Trim().ToLower() == "true"))  
  275.                 {  
  276.                     match = Regex.Match(html, m_loginUserNamePattern, RegexOptions.Compiled);  
  277.                     if (match.Success)  
  278.                     {  
  279.                         string name = match.Groups["name"].Value;  
  280.   
  281.   
  282.                         return "登录成功:" + name;  
  283.                     }  
  284.                     else  
  285.                     {  
  286.                        return "登录失败,未知错误";  
  287.                     }  
  288.                 }  
  289.                 else  
  290.                 {  
  291.                     return "登录失败!!!";  
  292.                 }  
  293.             }  
  294.         }  
  295.   
  296.   
  297.         /// <summary>  
  298.         /// Sets the cert policy.  
  299.         /// </summary>  
  300.         private static void SetCertificatePolicy()  
  301.         {  
  302.             ServicePointManager.ServerCertificateValidationCallback  
  303.                        += RemoteCertificateValidate;  
  304.         }  
  305.   
  306.   
  307.         /// <summary>  
  308.         /// Remotes the certificate validate.  
  309.         /// </summary>  
  310.         private static bool RemoteCertificateValidate(  
  311.            object sender, X509Certificate cert,  
  312.             X509Chain chain, SslPolicyErrors error)  
  313.         {  
  314.             SMessenger.NotifyColleagues(APPEND_MESSAGE, "信任任何证书...");  
  315.   
  316.   
  317.             return true;  
  318.         }  
  319.     }  
  320.   
  321.   
  322.     public class BeforLoginRnad  
  323.     {  
  324.         public string loginRand { getset; }  
  325.   
  326.   
  327.         public string randError { getset; }  
  328.     }  
注意登录时,主要的正文是:

                string parameter =
@"loginRand={0}&refundLogin=N&refundFlag=Y&isClick=&form_tk=null&loginUser.user_name={1}&nameErrorFocus=&user.password={2}&passwordErrorFocus=&randCode={3}&randErrorFocus=&NDU0NzY4NA%3D%3D=Nzg4ZDAxMGNkYTZlMTRjZA%3D%3D&myversion=undefined",它有三个参数,登录时的随机码,用户名,密码和验证码组成。


调用如下:
前台wpf代码:
[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <Window x:Class="Test12306AutoLogin.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         Title="MainWindow">  
  5.     <StackPanel>  
  6.         <Grid>  
  7.             <Grid.Resources>  
  8.                 <Style TargetType="TextBlock">  
  9.                     <Setter Property="FontFamily" Value="Microsoft YaHei"/>  
  10.                     <Setter Property="FontSize" Value="20"/>  
  11.                     <Setter Property="VerticalAlignment" Value="Center"/>  
  12.                 </Style>  
  13.   
  14.   
  15.                 <Style TargetType="TextBox">  
  16.                     <Setter Property="FontSize" Value="20"/>  
  17.                     <Setter Property="MinWidth" Value="300"/>  
  18.                     <Setter Property="Height" Value="50"/>  
  19.                     <Setter Property="VerticalAlignment" Value="Center"/>  
  20.                 </Style>  
  21.   
  22.   
  23.                 <Style TargetType="PasswordBox">  
  24.                     <Setter Property="FontSize" Value="20"/>  
  25.                     <Setter Property="MinWidth" Value="300"/>  
  26.                     <Setter Property="Height" Value="50"/>  
  27.                     <Setter Property="VerticalAlignment" Value="Center"/>  
  28.                 </Style>  
  29.             </Grid.Resources>  
  30.             <Grid.RowDefinitions>  
  31.                 <RowDefinition Height="auto"/>  
  32.                 <RowDefinition Height="auto"/>  
  33.                 <RowDefinition Height="auto"/>  
  34.                 <RowDefinition Height="auto"/>  
  35.             </Grid.RowDefinitions>  
  36.   
  37.   
  38.             <Grid.ColumnDefinitions>  
  39.                 <ColumnDefinition Width="auto"/>  
  40.                 <ColumnDefinition Width="auto"/>  
  41.             </Grid.ColumnDefinitions>  
  42.   
  43.   
  44.             <TextBlock Grid.Row="0" Grid.Column="0" Text="用户名:"/>  
  45.             <TextBox Grid.Row="0" Grid.Column="1" x:Name="txtUserName"/>  
  46.   
  47.   
  48.             <TextBlock Grid.Row="1" Grid.Column="0" Text="密 码:"/>  
  49.             <PasswordBox Grid.Row="1" Grid.Column="1" x:Name="txtPassword"/>  
  50.   
  51.   
  52.             <TextBlock Grid.Row="3" Grid.Column="0" Text="验证码"/>  
  53.             <StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal"  
  54.                         VerticalAlignment="Center">  
  55.                 <TextBox  x:Name="txtRandCode" Width="150"/>  
  56.                 <Image x:Name="imageRandCode" Width="70"/>  
  57.                 <Button Content="刷新验证码" Height="30" Width="80" Click="ButtonRefreshRandCode_Click" />  
  58.             </StackPanel>  
  59.         </Grid>  
  60.   
  61.   
  62.         <Button Content="登 录" Width="150" Height="50" Click="ButtonLogin_Click" />  
  63.   
  64.   
  65.         <RichTextBox x:Name="rtxResultContent"  MinHeight="200"/>  
  66.   
  67.   
  68.     </StackPanel>  
  69. </Window>  
后台代码:
[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public partial class MainWindow : Window  
  2.     {  
  3.         public MainWindow()  
  4.         {  
  5.             InitializeComponent();  
  6.   
  7.   
  8.             this.Loaded += new RoutedEventHandler(MainWindow_Loaded);  
  9.         }  
  10.   
  11.   
  12.         void MainWindow_Loaded(object sender, RoutedEventArgs e)  
  13.         {  
  14.             DoRefreshRandCode();  
  15.         }  
  16.   
  17.   
  18.         private void DoRefreshRandCode()  
  19.         {  
  20.             string imageRandUrl = Login12306Manager.RefreshCode();  
  21.   
  22.   
  23.             if (File.Exists(imageRandUrl))  
  24.             {  
  25.                 ImageSource src = (ImageSource)(new ImageSourceConverter().ConvertFromString(imageRandUrl));  
  26.   
  27.   
  28.                 this.imageRandCode.Source = src;  
  29.             }  
  30.   
  31.   
  32.             this.txtRandCode.Text = string.Empty;  
  33.         }  
  34.   
  35.   
  36.         /// <summary>  
  37.         /// 登录  
  38.         /// </summary>  
  39.         /// <param name="sender"></param>  
  40.         /// <param name="e"></param>  
  41.         private void ButtonLogin_Click(object sender, RoutedEventArgs e)  
  42.         {  
  43.             string userName = this.txtUserName.Text;  
  44.   
  45.   
  46.             string password = this.txtPassword.Password;  
  47.   
  48.   
  49.             string randCode = this.txtRandCode.Text;  
  50.   
  51.   
  52.             if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(randCode))  
  53.             {  
  54.                 MessageBox.Show("请填写完整信息");  
  55.   
  56.   
  57.                 return;  
  58.             }  
  59.   
  60.   
  61.             string html = Login12306Manager.Login(userName, password, randCode);  
  62.   
  63.   
  64.             System.Windows.Documents.FlowDocument doc = this.rtxResultContent.Document;  
  65.   
  66.   
  67.             doc.Blocks.Clear();  
  68.   
  69.   
  70.             this.rtxResultContent.AppendText(html);    
  71.         }  
  72.   
  73.   
  74.         /// <summary>  
  75.         /// 刷新验证码  
  76.         /// </summary>  
  77.         /// <param name="sender"></param>  
  78.         /// <param name="e"></param>  
  79.         private void ButtonRefreshRandCode_Click(object sender, RoutedEventArgs e)  
  80.         {  
  81.             DoRefreshRandCode();  
  82.         }  
  83.     }  
代码下载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值