private void _futureSellBtn_Click(object sender, EventArgs e) { HttpSender http = new HttpSender("https://fincloud.apex.com.tw/FinCloud/api/GVE/PutOrder"); HttpHeaderList header = new HttpHeaderList(); header.AddHeader("Content-Type", "application/json"); header.AddHeader("Host", "fincloud.apex.com.tw"); header.AddHeader("Referer", "https://fincloud.apex.com.tw/"); header.AddHeader("User-Agent", @"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"); CookieContainer cookies = new CookieContainer(); cookies.Add(_loginCookie); PutOrderPostReq req = new PutOrderPostReq { assetcode = "TXFJ8.tw", // 期貨商品(參數) bs = "S", //買賣(參數) dt = 0, //當沖單(參數) gmrid = this._gmrid, oct = "O", on = "IOC", // ot = "MKT", //限價或市價 price = 0, //價格(參) volume = 1 //量(參) }; ResponseResult rsp = http.SendRequest(HttpRequestMethod.Post, JsonConvert.SerializeObject(req), header, cookies); }
private OrderCaseManager(string gmrid, CookieCollection cookies, HttpHeaderList headers) { this._gmrid = gmrid; this._loginCookies = cookies; this._header = headers; this._caseOrderIdList = new List <string>(); this._orderList = new List <OrderListItem>(); this._dealList = new List <DealLogItem>(); this._errorList = new List <ErrorLogItem>(); }
private string _gmridApi = "http://www.fincloud.tw/FinCloud/api/GVE/GetGMRIDs"; //2019 private LoginManager() { _header = new HttpHeaderList(); _header.AddHeader("Content-Type", "application/json"); //_header.AddHeader("Host", "fincloud.apex.com.tw"); _header.AddHeader("Host", "www.fincloud.tw"); _header.AddHeader("Origin", "http://www.fincloud.tw"); //_header.AddHeader("Referer", "https://fincloud.apex.com.tw/"); // 2018 _header.AddHeader("Referer", "http://www.fincloud.tw/"); //2019 _header.AddHeader("User-Agent", @"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"); }
/// <summary> /// 下載借券資料 /// </summary> private void DownloadLendStockData() { string lastDateStr = _lastTradeDate.ToString("yyyyMMdd"); //http://www.tse.com.tw/zh/page/trading/exchange/TWT72U.html //證交所借券系統與證商/證金營業處所借券餘額合計表 string url = string.Format("http://www.tse.com.tw/exchangeReport/TWT72U?response=json&date={0}&selectType=SLBNLB", lastDateStr); HttpSender lendStockHttp = new HttpSender(url); HttpHeaderList lendStockHeader = new HttpHeaderList(); ResponseResult lendStockHttpResult = lendStockHttp.SendRequest(HttpRequestMethod.Get, "", lendStockHeader); LendStockRspMsg rspMsg = JsonConvert.DeserializeObject <LendStockRspMsg>(lendStockHttpResult.ResponseBody); //TODO:要不要把資料寫入檔案呢? foreach (List <string> stockData in rspMsg.data) { if (this._dataContainer.ContainsKey(stockData[0])) { DailyMarketTradeData tradeData = this._dataContainer[stockData[0]]; tradeData.SymbolName = string.IsNullOrEmpty(tradeData.SymbolName) ? stockData[1] : tradeData.SymbolName; tradeData.YesterdayLendStockBalance = Convert.ToDecimal(stockData[2].Replace(",", "")) / 1000; tradeData.TodayLendStockPlusCount = Convert.ToDecimal(stockData[3].Replace(",", "")) / 1000; tradeData.TodayLendStockReturnCount = Convert.ToDecimal(stockData[4].Replace(",", "")) / 1000; tradeData.TodayLendStockBalance = (Convert.ToDecimal(stockData[2].Replace(",", "")) + Convert.ToDecimal(stockData[3].Replace(",", "")) - Convert.ToDecimal(stockData[4].Replace(",", ""))) / 1000; } else { DailyMarketTradeData tradeData = new DailyMarketTradeData { Symbol = stockData[0], SymbolName = stockData[1], YesterdayLendStockBalance = Convert.ToDecimal(stockData[2].Replace(",", "")) / 1000, TodayLendStockPlusCount = Convert.ToDecimal(stockData[3].Replace(",", "")) / 1000, TodayLendStockReturnCount = Convert.ToDecimal(stockData[4].Replace(",", "")) / 1000, TodayLendStockBalance = (Convert.ToDecimal(stockData[2].Replace(",", "")) + Convert.ToDecimal(stockData[3].Replace(",", "")) - Convert.ToDecimal(stockData[4].Replace(",", ""))) / 1000 }; this._dataContainer.Add(stockData[0], tradeData); } } }
/// <summary> /// 解析Http Response的header /// </summary> /// <param name="response">HttpWebResponse 物件</param> /// <returns></returns> public static HttpHeaderList ParseResponseHeader(HttpWebResponse response) { HttpHeaderList headers = new HttpHeaderList(); if (response != null && response.Headers != null) { foreach (string headerKey in response.Headers.AllKeys) { headers.AddHeader(headerKey, response.Headers[headerKey]); } } return headers; }
/// <summary> /// 建立請求的頭檔 /// </summary> /// <param name="request"></param> /// <param name="headers"></param> /// <returns></returns> public static HttpWebRequest BuildRequestHeader(HttpWebRequest request, HttpHeaderList headers) { foreach (String h in headers.GetHeaderKeys()) { switch (h.Trim().ToLower()) { case "accept": request.Accept = headers.GetHeaderValue(h); break; case "accept-encoding": if (headers.GetHeaderValue(h).ToLower().Contains("gzip") && headers.GetHeaderValue(h).ToLower().Contains("deflate")) { request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } else if (headers.GetHeaderValue(h).ToLower().Contains("gzip")) { request.AutomaticDecompression = DecompressionMethods.GZip; } else if (headers.GetHeaderValue(h).ToLower().Contains("deflate")) { request.AutomaticDecompression = DecompressionMethods.Deflate; } break; case "authorization": request.PreAuthenticate = true; request.Headers.Add("Authorization", headers.GetHeaderValue(h)); break; case "connection": { string connectionValue = headers.GetHeaderValue(h).Trim().ToLower(); if (connectionValue.Contains("keep-alive")) { request.KeepAlive = true; } if (connectionValue.Contains("upgrade")) { request.Headers.Add("Connection", "Upgrade"); } } break; case "content-type": request.ContentType = headers.GetHeaderValue(h); break; case "content-length": request.ContentLength = Convert.ToInt64(headers.GetHeaderValue(h)); break; case "date": request.Date = Convert.ToDateTime(headers.GetHeaderValue(h)); break; case "expect": request.Expect = headers.GetHeaderValue(h); break; case "host": request.Host = headers.GetHeaderValue(h); break; case "if-modified-since": request.IfModifiedSince = Convert.ToDateTime(headers.GetHeaderValue(h)); break; case "referer": request.Referer = headers.GetHeaderValue(h); break; case "user-agent": request.UserAgent = headers.GetHeaderValue(h); break; default: request.Headers.Add(h, headers.GetHeaderValue(h)); break; } } return request; }
private string _sendFutureOrderApi = "http://www.fincloud.tw/FinCloud/api/GVE/PutOrder"; //2019 private FireOrderManager(string gmrid, CookieCollection cookies, HttpHeaderList headers) { this._gmrid = gmrid; this._loginCookies = cookies; this._header = headers; }
public static FireOrderManager GetInstance(string gmrid, CookieCollection cookies, HttpHeaderList headers) { if (_fireOrderMgrInstance == null) { _fireOrderMgrInstance = new FireOrderManager(gmrid, cookies, headers); } return(_fireOrderMgrInstance); }
public static OrderCaseManager GetInstance(string gmrid, CookieCollection cookies, HttpHeaderList headers) { if (_odrCaseMgrInstance == null) { _odrCaseMgrInstance = new OrderCaseManager(gmrid, cookies, headers); } return(_odrCaseMgrInstance); }
private void DownloadMarginTradeDataByType(string date, string st) { string url = string.Format("http://www.tse.com.tw/exchangeReport/MI_MARGN?response=json&date={0}&selectType={1}", date, st); HttpSender marginTradeHttp = new HttpSender(url); HttpHeaderList marginTradeHeader = new HttpHeaderList(); ResponseResult marginTradeResult = marginTradeHttp.SendRequest(HttpRequestMethod.Get, "", marginTradeHeader); bool isJson = false; try { JObject.Parse(marginTradeResult.ResponseBody); isJson = true; } catch (Exception e) { isJson = false; } if (isJson == false) { return; } MarginTradeRspMsg rspMsg = JsonConvert.DeserializeObject <MarginTradeRspMsg>(marginTradeResult.ResponseBody); foreach (List <string> stockData in rspMsg.data) { if (this._dataContainer.ContainsKey(stockData[0])) { DailyMarketTradeData tradeData = this._dataContainer[stockData[0]]; tradeData.SymbolName = string.IsNullOrEmpty(tradeData.SymbolName) ? stockData[1] : tradeData.SymbolName; tradeData.MarginBuy = Convert.ToDecimal(stockData[2].Replace(",", "")); tradeData.MarginSell = Convert.ToDecimal(stockData[3].Replace(",", "")); tradeData.MarginYesterdayBalance = Convert.ToDecimal(stockData[5].Replace(",", "")); tradeData.MarginTodayBalance = Convert.ToDecimal(stockData[6].Replace(",", "")); tradeData.MarginChange = Convert.ToDecimal(stockData[6].Replace(",", "")) - Convert.ToDecimal(stockData[5].Replace(",", "")); tradeData.LoanBuy = Convert.ToDecimal(stockData[8].Replace(",", "")); tradeData.LoanSell = Convert.ToDecimal(stockData[9].Replace(",", "")); tradeData.LoanYesterdayBalance = Convert.ToDecimal(stockData[11].Replace(",", "")); tradeData.LoanTodayBalance = Convert.ToDecimal(stockData[12].Replace(",", "")); tradeData.LoanChange = Convert.ToDecimal(stockData[12].Replace(",", "")) - Convert.ToDecimal(stockData[11].Replace(",", "")); } else { DailyMarketTradeData tradeData = new DailyMarketTradeData { Symbol = stockData[0], SymbolName = stockData[1], MarginBuy = Convert.ToDecimal(stockData[2].Replace(",", "")), MarginSell = Convert.ToDecimal(stockData[3].Replace(",", "")), MarginYesterdayBalance = Convert.ToDecimal(stockData[5].Replace(",", "")), MarginTodayBalance = Convert.ToDecimal(stockData[6].Replace(",", "")), MarginChange = Convert.ToDecimal(stockData[6].Replace(",", "")) - Convert.ToDecimal(stockData[5].Replace(",", "")), LoanBuy = Convert.ToDecimal(stockData[8].Replace(",", "")), LoanSell = Convert.ToDecimal(stockData[9].Replace(",", "")), LoanYesterdayBalance = Convert.ToDecimal(stockData[11].Replace(",", "")), LoanTodayBalance = Convert.ToDecimal(stockData[12].Replace(",", "")), LoanChange = Convert.ToDecimal(stockData[12].Replace(",", "")) - Convert.ToDecimal(stockData[11].Replace(",", "")), }; this._dataContainer.Add(stockData[0], tradeData); } } }
private ResponseResult SendOutRequest(HttpRequestMethod method, string body, HttpHeaderList header) { ResponseResult rspResult = new ResponseResult(); _request = (HttpWebRequest)WebRequest.Create(_uri); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; _request.Method = method.ToString().ToUpper(); _request = HeaderHelper.BuildRequestHeader(_request, header); //如果有要利用http body傳送的資料,才會用outputStream來送資料 if (method.ToString().ToUpper() != "GET" && !string.IsNullOrEmpty(body)) { Stream outStream = null; try { outStream = _request.GetRequestStream(); byte[] outData = _requestStreamEncoding.GetBytes(body); outStream.Write(outData, 0, outData.Length); } catch (WebException we) { if (we.Response == null) { rspResult.ErrorMsg = we.Status.ToString(); rspResult.IsResultError = true; return rspResult; } else { } } catch (NotSupportedException nse) { rspResult.ErrorMsg = nse.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (ProtocolViolationException pve) { rspResult.ErrorMsg = pve.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (InvalidOperationException ivoe) { rspResult.ErrorMsg = ivoe.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (Exception e) { rspResult.ErrorMsg = e.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } finally { if (outStream != null) { outStream.Close(); } } } try { _response = (HttpWebResponse)_request.GetResponse(); } catch (WebException we) { _response = (HttpWebResponse)we.Response; _responseHeader = HeaderHelper.ParseResponseHeader(_response); if (_response == null || string.IsNullOrEmpty(_response.CharacterSet)) { SetResponseEncoding(Encoding.UTF8); } else { SetResponseEncoding(Encoding.GetEncoding(_response.CharacterSet)); } Stream inputs = _response.GetResponseStream(); string respBody = string.Empty; using (StreamReader sr = new StreamReader(inputs, this._responseStreamEncoding)) { respBody = sr.ReadToEnd(); } string statusMsg = string.Format("({0})\r\n{1}", _response.StatusDescription, respBody); rspResult.Headers = _responseHeader; rspResult.IsResultError = true; rspResult.ResponseBody = respBody; rspResult.ErrorMsg = statusMsg; rspResult.StatusMsg = _response.StatusCode.ToString(); return rspResult; } catch (NotSupportedException nse) { rspResult.ErrorMsg = nse.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (ProtocolViolationException pve) { rspResult.ErrorMsg = pve.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (InvalidOperationException ivoe) { rspResult.ErrorMsg = ivoe.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (Exception e) { rspResult.ErrorMsg = e.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } _responseHeader = HeaderHelper.ParseResponseHeader(_response); if (_response == null || string.IsNullOrEmpty(_response.CharacterSet)) { SetResponseEncoding(Encoding.UTF8); } else { SetResponseEncoding(Encoding.GetEncoding(_response.CharacterSet)); } Stream inputStream = null; String responseString = string.Empty; try { inputStream = _response.GetResponseStream(); using (StreamReader sr = new StreamReader(inputStream, this._responseStreamEncoding)) { responseString = sr.ReadToEnd(); } } catch (ObjectDisposedException ode) { rspResult.ErrorMsg = ode.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (ProtocolViolationException pve) { rspResult.ErrorMsg = pve.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (OutOfMemoryException oome) { rspResult.ErrorMsg = oome.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (IOException ioe) { rspResult.ErrorMsg = ioe.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } catch (Exception e) { rspResult.ErrorMsg = e.StackTrace.ToString(); rspResult.IsResultError = true; return rspResult; } finally { if (inputStream != null) { inputStream.Close(); } _response.Close(); } rspResult.ResponseBody = responseString; rspResult.IsResultError = false; rspResult.Headers = _responseHeader; rspResult.StatusMsg = _response.StatusCode.ToString(); return rspResult; }
public ResponseResult SendRequest(HttpRequestMethod method, String body, HttpHeaderList header) { return SendOutRequest(method, body, header); }
public String SendRequest(String method, String body, HttpHeaderList header) { // change method string to enum ResponseResult result = SendOutRequest(ParseHttpMethod(method), body, header); return result.ResponseBody; }
protected override void HandleRequest(HttpHeaderList HttpHeaderList, Dictionary <string, string> Parameters, byte[] PostContent) { HandleRequestEvent.Set(); }
private void sendRqBtn_Click(object sender, EventArgs e) { httpRespHeaderTxt.Clear(); if (string.IsNullOrEmpty(schemaCmb.Text)) { MessageBox.Show("請選擇要使用 [ Http ] 或是 [ Https ] !"); } if (string.IsNullOrEmpty(urlTxt.Text)) { MessageBox.Show("請填寫 URL !"); } HttpSender http = new HttpSender(); http.SetRequestEncoding(Encoding.UTF8); try { http.SetUrl(string.Format("{0}{1}", schemaCmb.Text.Trim(), urlTxt.Text.Trim())); } catch (Exception ecp) { MessageBox.Show("請檢查Url是否有填寫或是否填寫正確!"); } HttpHeaderList headers = new HttpHeaderList(); foreach (DataGridViewRow r in headerGrdVw.Rows) { if (r.Cells[0].Value != null) { headers.AddHeader(r.Cells[0].Value.ToString(), r.Cells[1].Value.ToString()); } } ResponseResult result = http.SendRequest(http.ParseHttpMethod(methodCmb.Text.ToUpper()), httpBodyTxt.Text.Trim(), headers); HttpHeaderList respHeaders = http.GetResponseHeaders(); if (respHeaders != null) { httpRespHeaderTxt.Clear(); foreach (KeyValuePair<string, string> h in respHeaders.GetHeaderCollection()) { httpRespHeaderTxt.AppendText( string.Format("{0} : {1}\r\n", h.Key, h.Value)); } } httpRespBodyTxt.Text = result.ResponseBody; }
protected virtual void HandleRequest(HttpHeaderList HttpHeaderList, Dictionary <string, string> Parameters, byte[] PostContent) { }