公司需要一個能隨時監看 8591 行情表和交易情形的工具,所以就寫了這個小程式。

運作上大多數都是利用 HttpWebRequest 擷取 HTML 後再使用 Regex 分析所需要的數據即可,不過在會員登入上另外需要 CookieContainer 的配合才能達成。

至於驗證碼也是一樣用 HttpWebRequest 取得後再輸出 Bitmap 並取得驗證碼的 Session 值即可。

最後再加上擷取台灣銀行牌告匯率的資訊來計算匯率比值就收工了!

/// <summary>
/// Cookie Container
/// </summary>
public static CookieCollection mc = new CookieCollection();
public static CookieContainer myContainer = new CookieContainer();

/// <summary>
/// Get or Set the cookie header
/// </summary>
/// <returns>CookieHeader</returns>
public static string CookieHeader
{
  get { return _cookieHeader; }
  set { _cookieHeader = value; }
}

/// <summary>
/// Processing 8591.com.tw user login 
/// </summary>
/// <param name="accounts">User Account</param>
/// <param name="pwd">User Password</param>
/// <param name="verify">Verify Code</param>
/// <returns>Bool</returns>
public static bool LoginTo8591(string accounts, string pwd, string verify)
{
  string param = "accounts=" + accounts + "&pwd=" + pwd + "&verifyCode=" + verify + "&action=userLogin&saveAccounts=0&imageField2=";
  HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(login_url);
  byte[] bs = Encoding.UTF8.GetBytes(param);
  
  /* 將 Cookie Header 指派給 HttpWebRequest 並寫入其值 */
  req.CookieContainer = new CookieContainer();
  req.Headers.Add("cookie", CookieHeader);
  req.CookieContainer.SetCookies(new Uri(login_url), CookieHeader);

  req.Method = "POST";
  req.AllowAutoRedirect = false;
  req.KeepAlive = false;
  req.ProtocolVersion = HttpVersion.Version10;
  req.Headers.Add("Pragma", "no-cache");
  req.ContentType = "application/x-www-form-urlencoded";
  req.Referer = "https://www.8591.com.tw/index.php?module=user&action=login";
  req.ContentLength = bs.Length;
  req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
  req.Timeout = 10000;

  /* 強制通過 HTTPS 驗證 */
  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);

  try
  {
    using (resp = (HttpWebResponse)req.GetResponse())
    {
      ...... 略 ......
    }
  }
  catch ( Exception )
  {
    ...... 略 ......
  }

}

/// <summary>
/// Passing SSL authorize
/// </summary>
/// <returns>Bool</returns>
public static bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
  return true;
}