public static ArrayList GetHtmlData(RequestPackage package) { HttpWebRequest request; HttpWebResponse response; ArrayList list = new ArrayList(); request = WebRequest.Create(HOST_URL + package.RequestURL) as HttpWebRequest; request.Referer = HOST_URL + package.RefererURL; request.Method = EHttpMethod.Get.ToString(); request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko"; request.KeepAlive = true; request.CookieContainer = Cookie; try { //获取服务器返回的资源 using (response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { Cookie.Add(response.Cookies); //保存Cookies list.Add(Cookie); list.Add(reader.ReadToEnd()); list.Add(Guid.NewGuid().ToString());//图片名 } } } catch (WebException ex) { list.Clear(); list.Add("发生异常/n/r"); WebResponse wr = ex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Clear(); list.Add("5"); list.Add("发生异常:" + ex.Message); } return list; }
public static Stream DownloadCode(RequestPackage package) { Stream stream = null; string url = HOST_URL + package.RequestURL; if (package.Params.Count > 0) url = string.Format("{0}?{1}", url, JoinParams(package.Params)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //属性配置 request.AllowWriteStreamBuffering = true; request.Credentials = System.Net.CredentialCache.DefaultCredentials; request.MaximumResponseHeadersLength = -1; request.Accept = "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko"; request.Method = EHttpMethod.Get.ToString(); request.Headers.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.5"); request.Headers.Add("Accept-Encoding", "gzip,deflate"); request.KeepAlive = true; request.CookieContainer = Cookie; try { //获取服务器返回的资源 using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse()) { using (Stream st = webResponse.GetResponseStream()) { stream = new MemoryStream(); while (true) { int data = st.ReadByte(); if (data == -1) break; stream.WriteByte((byte)data); } } } } catch (WebException) { stream = null; } catch (Exception) { stream = null; } return stream; }
protected override void OnShown(EventArgs e) { base.OnShown(e); PWLoading.Show(this, "正在获取相关数据,请稍后...", new Action(() => { if (RequestSubmitOrder()) { // 获取页面信息 RequestPackage request = new RequestPackage(); request.RequestURL = "/otn/confirmPassenger/initDc"; request.RefererURL = "/otn/leftTicket/init"; request.Params.Add("_json_att=", string.Empty); request.Method = "post"; ArrayList list = HttpContext.GetHtmlData(request); if (IsInit = (list.Count == 3)) { GetValidateCode(); string html_text = list[1].ToString(); // 获取 Token SubmitToken = StringExt.FindJsValue(html_text, "globalRepeatSubmitToken"); // 获取 ticketInfoForPassengerForm string ticketInfoForPassenger = StringExt.FindJsValue(html_text, "ticketInfoForPassengerForm"); TicketInfo = JsonConvert.DeserializeObject<TicketInfoForPassengerForm>(ticketInfoForPassenger); if (this.InvokeRequired) { this.Invoke(new Action(() => { this.LoadData(); this.UpdatePassengers(); })); } else { this.LoadData(); this.UpdatePassengers(); } } else { Log.Log.Write(list); } } })); }
public static QueryTrainData[] Query(string fromStation, string toStation, string date) { QueryTrainData[] data = null; ResponseQuery response = null; RequestPackage request = new RequestPackage(); request.Method = EHttpMethod.Get.ToString(); request.RefererURL = "/otn/leftTicket/init"; request.RequestURL = "/otn/leftTicket/query"; request.Params.Add("leftTicketDTO.train_date", date); request.Params.Add("leftTicketDTO.from_station", fromStation); request.Params.Add("leftTicketDTO.to_station", toStation); request.Params.Add("purpose_codes", "ADULT"); Label_001: ArrayList list = HttpContext.Send(request); if (list.Count == 2) { string jsonString = Encoding.UTF8.GetString(list[1] as byte[]); response = JsonConvert.DeserializeObject<ResponseQuery>(jsonString); if (response.status) { data = response.Data; } else if (response.messages != null && response.messages.Length > 0) { throw new Exception(response.messages[0]); } else if (!string.IsNullOrEmpty(response.c_url)) { request.RequestURL = "/otn/" + response.c_url; goto Label_001; } } else { Log.Log.Write(list); } return data; }
/// <summary> /// 登录 12306 /// </summary> void btnLogin_Click(object sender, EventArgs e) { try { this.btnLogin.Enabled = false; AppContext.Tip.Show( "正在登录...", this, this.btnLogin.Location.X, this.btnLogin.Location.Y - 20); string loginName = this.txtLoginName.Text.Trim(); string loginPwd = this.txtLoginPwd.Text.Trim(); string code = this.txtCode.Text.Trim(); PWLoading.Show(this, "正在登录...", new Action(() => { RequestPackage request = new RequestPackage(); request.Params.Add("loginUserDTO.user_name", System.Web.HttpUtility.UrlEncode(loginName)); request.Params.Add("userDTO.password", System.Web.HttpUtility.UrlEncode(loginPwd)); request.Params.Add("randCode", System.Web.HttpUtility.UrlEncode(code)); request.RequestURL = "/otn/login/loginAysnSuggest"; request.RefererURL = "/otn/login/init"; request.Method = "post"; ArrayList list = HttpContext.Send(request); if (list.Count == 2) { string jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); ResponseLogin package = JsonConvert.DeserializeObject<ResponseLogin>(jsonResult); if (package.Data != null && package.Data.loginCheck == "Y") { AppContext.LoginUser = new LoginUser() { UserName = loginName, Password = loginPwd, }; this.DialogResult = DialogResult.OK; } else { if (package.messages != null && package.messages.Length > 0) { if (this.InvokeRequired) { this.Invoke(new Action(() => { MessageBox.Show(this, package.messages[0], "提示"); this.btnLogin.Enabled = true; this.GetValidateCode(); this.txtCode.Focus(); })); } } } } else { Log.Log.Write(list); } })); } catch (Exception ex) { MessageBox.Show(this, "错误:" + ex.Message, "系统错误"); this.btnLogin.Enabled = true; } }
/// <summary> /// 获取验证码 /// </summary> private void GetValidateCode() { try { // 启动计时器 if (!this.timer.Enabled) { this._res_index = 1; this.timer.Start(); } this.txtCode.Text = string.Empty; ThreadPool.QueueUserWorkItem((obj) => { RequestPackage request = new RequestPackage("/otn/login/init"); ArrayList list = HttpContext.GetHtmlData(request); if (list.Count == 3) { string path = Path.Combine(AppContext.ValidateCode_Path, list[2] + ".png"); request.RequestURL = "/otn/passcodeNew/getPassCodeNew"; request.Params.Add("module", "login"); request.Params.Add("rand", "sjrand"); using (Stream stream = HttpContext.DownloadCode(request)) { if (this.InvokeRequired) { this.Invoke(new Action(() => { this.ShowValidateCode(stream); })); } else { this.ShowValidateCode(stream); } } } else { Log.Log.Write(list); } }); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "系统提示"); } }
public static ArrayList Send(RequestPackage package) { ArrayList list = new ArrayList(); HttpWebRequest request = null; HttpWebResponse response = null; string url = HOST_URL + package.RequestURL; string method = package.Method.ToString().ToLower(); if (package.Method.ToLower() == EHttpMethod.Get.ToString().ToLower()) { if (package.Params.Count > 0) url = string.Format("{0}?{1}", url, JoinParams(package.Params)); request = WebRequest.Create(url) as HttpWebRequest; request.Accept = package.Accept; request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko"; request.CookieContainer = Cookie; request.Referer = HOST_URL + package.RefererURL; request.Method = method; } else { request = WebRequest.Create(url) as HttpWebRequest; string data = JoinParams(package.Params); byte[] b = package.Encoding.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Accept = package.Accept; request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko"; request.CookieContainer = Cookie; request.Referer = HOST_URL + package.RefererURL; request.Method = method; request.ContentLength = b.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); } } try { //获取服务器返回的资源 using (response = request.GetResponse() as HttpWebResponse) { using (Stream stream = response.GetResponseStream()) { if (response.Cookies.Count > 0) { Cookie.Add(response.Cookies); } list.Add(Cookie); List<byte> dataList = new List<byte>(); while (true) { int data = stream.ReadByte(); if (data == -1) break; dataList.Add((byte)data); } list.Add(dataList.ToArray()); } } } catch (WebException wex) { WebResponse wr = wex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.UTF8)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Add("发生异常/n/r" + ex.Message); } return list; }
/// <summary> /// 提交订单 /// </summary> private bool SubmitOrder(string passengerTicketStr, string oldPassengerStr, string code) { bool result = false; PWLoading.Show(this, "正在检查订单,请稍后...", new Action(() => { RequestPackage request = new RequestPackage(); request.Encoding = Encoding.UTF8; request.Method = "post"; request.RefererURL = "/otn/confirmPassenger/initDc"; request.RequestURL = "/otn/confirmPassenger/checkOrderInfo"; request.Params.Add("cancel_flag", "2"); request.Params.Add("bed_level_order_num", "000000000000000000000000000000"); request.Params.Add("passengerTicketStr", passengerTicketStr); request.Params.Add("oldPassengerStr", oldPassengerStr); request.Params.Add("tour_flag", TicketInfo.tour_flag); request.Params.Add("randCode", code); request.Params.Add("_json_att", string.Empty); request.Params.Add("REPEAT_SUBMIT_TOKEN", SubmitToken); ArrayList list = HttpContext.Send(request); if (list.Count == 2) { PWLoading.UpdateMessage("正在查询余票数量..."); string jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); ResponseBase response = JsonConvert.DeserializeObject<ResponseCheckOrderInfo>(jsonResult); if (response.status) { ResponseCheckOrderInfo res_check_order = response as ResponseCheckOrderInfo; if (res_check_order.Data.submitStatus) { string date = TicketInfo.queryLeftTicketRequestDTO.TrainDate.ToString("ddd MMM dd yyyy 00:00:00 ", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")) + "GMT + 0800(中国标准时间)"; string train_date = Data.QueryLeftNewDTO.StartTrainDate.ToString( "ddd MMM dd yyyy 00:00:00 ", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")) + "GMT + 0800(中国标准时间)"; request.RequestURL = "/otn/confirmPassenger/getQueueCount"; request.RefererURL = "/otn/confirmPassenger/initDc"; request.Params.Clear(); request.Params.Add("train_date", System.Web.HttpUtility.UrlEncode(train_date)); request.Params.Add("train_no", System.Web.HttpUtility.UrlEncode(Data.QueryLeftNewDTO.train_no)); request.Params.Add("stationTrainCode", System.Web.HttpUtility.UrlEncode(Data.QueryLeftNewDTO.station_train_code)); request.Params.Add("seatType", System.Web.HttpUtility.UrlEncode("0")); request.Params.Add("fromStationTelecode", System.Web.HttpUtility.UrlEncode(Data.QueryLeftNewDTO.from_station_telecode)); request.Params.Add("toStationTelecode", System.Web.HttpUtility.UrlEncode(Data.QueryLeftNewDTO.to_station_telecode)); request.Params.Add("leftTicket", System.Web.HttpUtility.UrlEncode(Data.QueryLeftNewDTO.yp_info)); request.Params.Add("purpose_codes", System.Web.HttpUtility.UrlEncode("00")); request.Params.Add("_json_att", string.Empty); request.Params.Add("REPEAT_SUBMIT_TOKEN", System.Web.HttpUtility.UrlEncode(SubmitToken)); list = HttpContext.Send(request); if (list.Count == 2) { PWLoading.UpdateMessage("正在确认订单..."); jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); response = JsonConvert.DeserializeObject<ResponseQueueCount>(jsonResult); if (response.status) { request.RequestURL = "/otn/confirmPassenger/confirmSingleForQueue"; request.RefererURL = "/otn/confirmPassenger/initDc"; request.Params.Clear(); request.Params.Add("passengerTicketStr", passengerTicketStr); request.Params.Add("oldPassengerStr", oldPassengerStr); request.Params.Add("randCode", code); request.Params.Add("purpose_codes", TicketInfo.purpose_codes); request.Params.Add("key_check_isChange", TicketInfo.key_check_isChange); request.Params.Add("leftTicketStr", TicketInfo.leftTicketStr); request.Params.Add("train_location", TicketInfo.train_location); request.Params.Add("_json_att", string.Empty); request.Params.Add("REPEAT_SUBMIT_TOKEN", SubmitToken); list = HttpContext.Send(request); jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); response = JsonConvert.DeserializeObject<ResponseSubmit>(jsonResult); if (response.status) { if ((response as ResponseSubmit).Data.submitStatus) { result = true; } } } } else { Log.Log.Write(list); } } else { Log.Log.Write(list); throw new Exception(res_check_order.Data.errMsg); } } else if (response.messages != null && response.messages.Length > 0) { string message = response.messages[0]; Log.Log.Write(list); throw new Exception(message); } } else { Log.Log.Write(list); } })); return result; }
/// <summary> /// 请求提交订单 /// </summary> /// <returns></returns> private bool RequestSubmitOrder() { bool result = false; if (Data != null) { RequestPackage request = new RequestPackage(); request.Encoding = Encoding.UTF8; request.RequestURL = "/otn/leftTicket/submitOrderRequest"; request.RefererURL = "/otn/leftTicket/init"; request.Params.Add("secretStr", Data.secretStr); request.Params.Add("train_date", Data.QueryLeftNewDTO.StartTrainDate.ToString("yyyy-MM-dd")); request.Params.Add("back_train_date", DateTime.Now.ToString("yyyy-MM-dd")); request.Params.Add("tour_flag", "dc"); request.Params.Add("purpose_codes", "ADULT"); request.Params.Add("query_from_station_name", Data.QueryLeftNewDTO.from_station_name); request.Params.Add("query_to_station_name", Data.QueryLeftNewDTO.to_station_name); ArrayList list = HttpContext.Send(request); if (list.Count == 2) { string jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); try { ResponseBase response = JsonConvert.DeserializeObject<ResponseBase>(jsonResult); if (response.status) { result = true; } else if (response.messages != null && response.messages.Length > 0) { throw new Exception(response.messages[0]); } } catch { throw new Exception("网络可能存在问题,请重试!"); } } else { Log.Log.Write(list); } } return result; }
/// <summary> /// 获取验证码 /// </summary> private void GetValidateCode() { try { if (this.InvokeRequired) { this.Invoke(new Action(() => { this.StartTimer(); this.txtCode.Text = string.Empty; })); } else { this.StartTimer(); this.txtCode.Text = string.Empty; } // 获取验证码 RequestPackage request = new RequestPackage(); request.RequestURL = "/otn/passcodeNew/getPassCodeNew"; request.Params.Add("module", "passenger"); request.Params.Add("rand", "randp"); using (Stream stream = HttpContext.DownloadCode(request)) { if (this.InvokeRequired) { this.Invoke(new Action(() => { this.ShowValidateCode(stream); })); } else { this.ShowValidateCode(stream); } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, "系统提示"); } }
/// <summary> /// 验查用户登录状态 /// </summary> /// <returns>是否需要重新登录</returns> private bool CheckUser() { bool result = false; // 检查登录状态 RequestPackage request = new RequestPackage() { Method = "post", RequestURL = "/otn/login/checkUser", RefererURL = "/otn/leftTicket/init", }; request.Params.Add("_json_att", string.Empty); ArrayList list = HttpContext.Send(request); if (list.Count == 2) { string jsonResult = Encoding.UTF8.GetString(list[1] as byte[]); ResponseCheckLogin response = JsonConvert.DeserializeObject<ResponseCheckLogin>(jsonResult); result = response.Data.flag; } else { Log.Log.Write(list); } return result; }