/// <summary> /// 公共处理post请求 /// </summary> /// <typeparam name="T">请求参数对象</typeparam> /// <typeparam name="T1">返回的data对象</typeparam> /// <param name="host">主机名</param> /// <param name="url">请求地址</param> /// <param name="param">请求参数对象</param> /// <param name="timeout">超时时间,单位:秒,默认为30秒</param> /// <returns>返回对象</returns> public static ReturnBody <T1> CommonHttpRequestForPost <T, T1>(string host, string url, T param, int timeout = 30) { try { Guid guid = Guid.NewGuid(); WipLogHelper.WriteRequestRecord <T>(host, url, param, guid); JavaScriptDateTimeConverter convert = new JavaScriptDateTimeConverter(); var strParam = JsonConvert.SerializeObject(param, Formatting.None, convert);//序列化后的字符串 string content = new HTTPHelper(host).postContentForString(url, strParam, new Guid(), timeout); WipLogHelper.WriteRequestRecord <T>(host, url, param, guid, content); if (!string.IsNullOrEmpty(content)) { ReturnBody <T1> result = JsonConvert.DeserializeObject <ReturnBody <T1> >(content); if (result != null) { return(result); } } } catch (Exception) { throw; } return(null); }
private IEnumerable <HouseInfo> GetRoomList(string url) { var htmlResult = HTTPHelper.GetHTMLByURL(url); var page = new AngleSharp.Parser.Html.HtmlParser().Parse(htmlResult); return(page.QuerySelector("ul.screening_left_ul").QuerySelectorAll("li").Select(element => { var screening_time = element.QuerySelector("p.screening_time").TextContent; var screening_price = element.QuerySelector("h5").TextContent; var locationInfo = element.QuerySelector("a"); var locationContent = locationInfo.TextContent.Split(',').FirstOrDefault(); var location = locationContent.Remove(0, locationContent.IndexOf("租") + 1); decimal housePrice = 0; decimal.TryParse(screening_price.Replace("¥", "").Replace("元/月", ""), out housePrice); var markBGType = (housePrice / 1000) > (int)LocationMarkBGType.Black ? LocationMarkBGType.Black : (LocationMarkBGType)(housePrice / 1000); return new HouseInfo { Money = screening_price, HouseURL = "http://www.huzhumaifang.com" + locationInfo.GetAttribute("href"), HouseLocation = location, HouseTime = screening_time, HousePrice = housePrice, LocationMarkBG = markBGType.ToString() + ".PNG", }; })); }
/// <summary> /// 登录注册页——登录命令 /// </summary> private async void UCOrderLoginandRegisterLoginCommandExecute() { try { if (OrderLoginUserName != "" && OrderLoginPassword != "") { ResultData resultData = await HTTPHelper.Login(LoginModeEnum.LoginbyUserName, OrderLoginUserName, OrderLoginPassword); if (resultData.Code == ErrorCode.OK)//登录成功 { UserControlSwitchFunc(UserControlSwitchEnum.UCOrderExterior); } if (resultData.Code == ErrorCode.WrongParameter)//用户名或密码错误 { MessageBox.Show("用户名或密码错误!"); } } else { MessageBox.Show("用户名或密码不能为空!"); } } catch (Exception) { MessageBox.Show("访问HTTP服务器时出错!"); } }
private int GetPageNumByIndex(string cnName) { var url = $"http://{cnName}.58.com/zufang/pn1/?isreal=true"; var htmlResult = HTTPHelper.GetHTMLByURL(url); return(ParsePages(htmlResult)); }
/// <summary> /// 从服务器获取视频流的相关信息 /// </summary> /// <param name="url"></param> /// <returns></returns> private string getThirdUrl(string url) { String responseString = HTTPHelper.SendHTTPGetRequest(url); responseString = System.Web.HttpUtility.UrlDecode(responseString); return(responseString); }
private string applyFile() { log.DebugFormat("Importing Rio-style XVA from {0} to SR {1}", m_filename, SR.Name()); Host host = SR.GetStorageHost(); string hostURL; if (host == null) { Uri uri = new Uri(Session.Url); hostURL = uri.Host; } else { log.DebugFormat("SR is not shared -- redirecting to {0}", host.address); hostURL = host.address; } log.DebugFormat("Using {0} for import", hostURL); return(HTTPHelper.Put(this, HTTP_PUT_TIMEOUT, m_filename, hostURL, (HTTP_actions.put_ssbbs)HTTP_actions.put_import, Session.opaque_ref, false, false, SR.opaque_ref)); }
private IEnumerable <HouseInfo> GetRoomListByIndex(string cnName, int index) { var url = $"http://{cnName}.58.com/zufang/pn{index}/?isreal=true"; var htmlResult = HTTPHelper.GetHTMLByURL(url); var page = new HtmlParser().Parse(htmlResult); var houseList = page.QuerySelectorAll("tr[logr]").Where(room => room.QuerySelector("b.pri") != null).Select(room => { decimal housePrice = 0; decimal.TryParse(room.QuerySelector("b.pri").TextContent, out housePrice); var markBGType = (housePrice / 1000) > (int)LocationMarkBGType.Black ? LocationMarkBGType.Black : (LocationMarkBGType)(housePrice / 1000); return(new HouseInfo { // HouseLocation=room.QuerySelector("a.a_xq1").TextContent.Replace("租房",""), HouseLocation = room.QuerySelector("span.f12") != null && !string.IsNullOrEmpty(room.QuerySelector("span.f12").TextContent) ? room.QuerySelector("span.f12").TextContent.Replace("租房", "") : room.QuerySelector("a.a_xq1") != null && !string.IsNullOrEmpty(room.QuerySelector("a.a_xq1").TextContent) ? room.QuerySelector("a.a_xq1").TextContent.Replace("租房", "") : "", HouseTitle = room.QuerySelector("a.t") != null ? room.QuerySelector("a.t").TextContent : "", Money = room.QuerySelector("b.pri") != null ? room.QuerySelector("b.pri").TextContent : "", HouseURL = $"http://{cnName}.58.com/zufang/{room.GetAttribute("logr").Split('_')[3]}x.shtml", LocationMarkBG = markBGType.ToString() + ".png", }); }); return(houseList.Where(room => !string.IsNullOrEmpty(room.HouseLocation) && !string.IsNullOrEmpty(room.HouseTitle) && !string.IsNullOrEmpty(room.Money))); }
private void ConnectHostedConsole(VNCGraphicsClient v, Console console) { Program.AssertOffEventThread(); Host host = console.Connection.Resolve(Source.resident_on); if (host == null) { throw new Failure(Failure.INTERNAL_ERROR, Messages.VNC_HOST_GONE); } Uri uri = new Uri(console.location); String SessionUUID; lock (activeSessionLock) { // use the elevated credentials, if provided, for connecting to the console (CA-91132) activeSession = (string.IsNullOrEmpty(ElevatedUsername) || string.IsNullOrEmpty(ElevatedPassword)) ? console.Connection.DuplicateSession() : console.Connection.ElevatedSession(ElevatedUsername, ElevatedPassword); SessionUUID = activeSession.uuid; } Stream stream = HTTPHelper.CONNECT(uri, console.Connection, SessionUUID, false, true); InvokeConnection(v, stream, console); }
private string applyFile() { log.DebugFormat("Importing Rio-style XVA from {0} to SR {1}", m_filename, SR.Name); Host host = SR.GetStorageHost(); string hostURL; if (host == null) { Uri uri = new Uri(Session.Url); hostURL = uri.Host; } else { log.DebugFormat("SR is not shared -- redirecting to {0}", host.address); hostURL = host.address; } //添加port int port = Connection != null ? Connection.Port : HTTP.DEFAULT_HTTPS_PORT; if (port != 0) { hostURL = hostURL + ":" + port; //ip:port } log.DebugFormat("Using {0} for import", hostURL); return(HTTPHelper.Put(this, HTTP_PUT_TIMEOUT, m_filename, hostURL, (HTTP_actions.put_ssbbs)HTTP_actions.put_import, Session.uuid, false, false, SR.opaque_ref)); }
public static string Post(string uri, RequestMessage data, string contentType, string method = "POST") { try { byte[] dataBytes = HTTPHelper.ConvertBytesFromObject(data); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.ContentLength = dataBytes.Length; request.ContentType = contentType; request.Method = method; using (Stream requestBody = request.GetRequestStream()) { requestBody.Write(dataBytes, 0, dataBytes.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } } } } catch (Exception exp) { Console.WriteLine(exp.Message); return(string.Empty); } }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <returns></returns> public Media Extract(String url) { String responseString = HTTPHelper.SendHTTPGetRequest(url); Regex regex = new Regex("[^<]<video\\s+[^>]*src=['\"]?([^\\s'\"]+)['\"][^>]*>"); if (regex.IsMatch(responseString)) { Match m = regex.Match(responseString); List <Stream> streams = new List <Stream>(); while (m != null) { String src = m.Groups[1].Value; if (src != null) { streams.Add(new Stream(StreamType.Unknown, new List <string> { src })); } m = m.NextMatch(); } if (streams.Count > 0) { return(new Media(url, streams.ToArray(), 0)); } } return(null); }
public static string CheckUpdate() { string result = string.Empty; try { string updatePage = String.Empty; switch (Brand.Brand.Name) { case "Umax": { updatePage = HTTPHelper.DownloadWebPage("http://umaxsoft.com/PrivateArea/Updater/UDS2012"); break; } } if (updatePage != String.Empty) { //Parse version //Parse url //return true; } } catch (Exception) { } return(result); }
public ActionResult AddPhone(Phone phone, int id) { phone.PersonID = id; HTTPHelper.Add <Phone>("http://localhost:53006/", "Phone/AddPhone", phone, Method.POST); return(RedirectToAction("GetPersons", "Person")); }
public ActionResult GetPhone(int id) { List <Phone> phones = new List <Phone>(); phones = HTTPHelper.GetList <List <Phone> >("http://localhost:53006/", "Phone/GetPhone", Method.GET, id); return(View(phones)); }
/// <summary> /// 订单状态页——提交取件命令 /// </summary> /// <param name="obj">订单号</param> private async void UCTakeOrderOrderStateSubmitOrderCommandExecute(object obj) { GridCurrentUserControlIsVisible(); try { ResultData resultData = await HTTPHelper.TakeOrder(obj.ToString()); if (resultData.Result == "OK")//取单递交成功 { if (resultData.Code == ErrorCode.OK) { UserControlSwitchFunc(UserControlSwitchEnum.UCTakeOrderSubmitOrderResult); TimerStart(10); } } if (resultData.Result == "NA")//取单递交失败 { if (resultData.Code == ErrorCode.UserNotLogined) { MessageBox.Show("用户未登录!"); } if (resultData.Code == ErrorCode.Exception) { MessageBox.Show("异常!"); } } } catch (Exception) { MessageBox.Show("访问HTTP服务器时出错!"); } }
// GET: Person public ActionResult Index() { List <Person> personList = new List <Person>(); personList = HTTPHelper.SendRequest <List <Person> >("http://localhost:64908", "Guide/Guide", Method.GET); return(View(personList)); }
/// <summary> /// 订单状态页——查询订单状态刷新指令 /// </summary> private async void UCTakeOrderOrderStateQueryRefreshCommandExecute() { try { OrderStateListDto orderStateListDtos = await HTTPHelper.QueryOrder(); App.Current.Dispatcher.Invoke(() => { OrderStateList.Clear(); });//更新新的数据之前先清空列表 foreach (var item in orderStateListDtos.States) { var list = new OrderStateModel { OrderID = item.OrderID, OrderStartTime = item.OrderStartTime, CurrentState = item.CurrentState, ProcessingName = item.ProcessingName, TakeOrderIsOK = item.CurrentState == "Finished", }; App.Current.Dispatcher.Invoke(() => { OrderStateList.Add(list); }); } } catch (Exception) { MessageBox.Show("访问HTTP服务器时出错!"); } }
protected override string ExecuteCommand(string[] args) { // Get the bounds of the virtual screen int left = SystemInformation.VirtualScreen.Left; int top = SystemInformation.VirtualScreen.Top; int width = SystemInformation.VirtualScreen.Width; int height = SystemInformation.VirtualScreen.Height; // Totally not a shady name string path = FileHelper.GetTemporaryFilePath("cortana.png"); // Create a new bitmap using (Bitmap bmp = new Bitmap(width, height)) { // Get the graphics using (Graphics g = Graphics.FromImage(bmp)) { // Copy the screen g.CopyFromScreen(left, top, 0, 0, bmp.Size); } bmp.Save(path); } string url = HTTPHelper.Upload(path); FileHelper.DeleteFile(path); return(url); }
/// <summary> /// UpdaterThread Thread /// </summary> private void Get(ArchiveInterval interval, URIDelegate URI, ReaderDelegate Reader, Host host, IXenObject xenObject) { if (host == null) { return; } try { Session session = xenObject.Connection.Session; if (session == null) { return; } using (Stream httpstream = HTTPHelper.GET(URI(session, host, interval, xenObject), xenObject.Connection, true, false)) { using (XmlReader reader = XmlReader.Create(httpstream)) { SetsAdded = new List <DataSet>(); while (reader.Read()) { Reader(reader, xenObject); } } } } catch (WebException) { } catch (Exception e) { log.Debug(string.Format("ArchiveMaintainer: Get updates for {0}: {1} Failed.", xenObject is Host ? "Host" : "VM", xenObject != null ? xenObject.opaque_ref : Helper.NullOpaqueRef), e); } }
public async Task <ActionResult> Devices() { // Manage session and Context HttpServiceUriBuilder contextUri = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName); if (HTTPHelper.IsSessionExpired(HttpContext, this)) { return(Redirect(contextUri.GetServiceNameSiteHomePath())); } else { this.ViewData["TargetSite"] = contextUri.GetServiceNameSite(); this.ViewData["PageTitle"] = "Devices"; this.ViewData["HeaderTitle"] = "Devices Dashboard"; string reportUniqueId = FnvHash.GetUniqueId(); string reportName = "PSG-VibrationDeviceReport-02"; // the dashboard EmbedConfig task = await ReportsHandler.GetEmbedReportConfigData(ClientId, GroupId, Username, Password, AuthorityUrl, ResourceUrl, ApiUrl, reportUniqueId, reportName, this.context, ServiceEventSource.Current); this.ViewData["EmbedToken"] = task.EmbedToken.Token; this.ViewData["EmbedURL"] = task.EmbedUrl; this.ViewData["EmbedId"] = task.Id; this.ViewData["ReportUniqueId"] = ""; return(this.View()); } }
private int GetPageNum(int costFrom, int costTo, string cnName) { var url = $"http://{cnName}.58.com/zufang/pn1/?isreal=true&minprice={costFrom}_{costTo}"; var htmlResult = HTTPHelper.GetHTMLByURL(url); return(ParsePages(htmlResult)); }
protected override string ExecuteCommand(string[] args) { File.Move(FileHelper.GetBinaryPath(), FileHelper.GetBinaryOldPath()); int status = HTTPHelper.Download(args[0], FileHelper.GetBinaryPath()); if (status != 0) { File.Move(FileHelper.GetBinaryOldPath(), FileHelper.GetBinaryPath()); return("Updated failed..."); } ProcessStartInfo info = new ProcessStartInfo(FileHelper.GetBinaryPath()) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; Process process = new Process() { StartInfo = info }; process.Start(); Environment.Exit(0); // Should never reach this point. return("System exit failed: !!" + process.StandardOutput.ReadToEnd()); }
private void HttpGet(Uri uri) { int BUFSIZE = 1024; byte[] buf = new byte[BUFSIZE]; using (MemoryStream ms = new MemoryStream()) { using (Stream http = HTTPHelper.GET(uri, Connection, false, true)) { while (true) { int n = http.Read(buf, 0, BUFSIZE); if (n <= 0) { result = new String(Encoding.UTF8.GetChars(ms.ToArray())); return; } ms.Write(buf, 0, n); if (Cancelling) { return; } } } } }
public static string DoClick(CorpRecEventClick instanse) { string strResult = string.Empty; if ("2".Equals(instanse.EventKey)) { try { string flag = HTTPHelper.GetRequest(logoutURL + "?openid=" + instanse.FromUserName); if (bool.Parse(flag)) { CorpSendMsgText msg = new CorpSendMsgText("解除绑定成功!", instanse.ToUserName, agentid); corpCore.SendMsg(msg); } } catch (Exception e) { log.Error("PubWeChatDsta DoClick Logout Err:", e); } } else { CorpSendMsgText msg = new CorpSendMsgText("开发中,敬请期待!", instanse.ToUserName, agentid); corpCore.SendMsg(msg); } return(strResult); }
private int GetPageCount(string indexURL) { var htmlResult = HTTPHelper.GetHTMLByURL(indexURL); var page = new AngleSharp.Parser.Html.HtmlParser().Parse(htmlResult); return(Convert.ToInt32(page.QuerySelector("a.end")?.TextContent ?? "0")); }
/// <summary> /// 订单提交页——确认提交订单 /// </summary> private async void UCOrderSubmitOrderSubmitConfirmCommandExecute() { GridCurrentUserControlIsVisible(); try { AddOrderResult addOrderResult = await HTTPHelper.SubmitOrder(MarkingInfo, GetCoordinates()); if (addOrderResult.Result == "OK") { OrderSubmitResult = "您的订单提交成功,订单号为:" + addOrderResult.OrderID; UserControlSwitchFunc(UserControlSwitchEnum.UCOrderSubmitOrderResult); } if (addOrderResult.Result == "NA") { if (addOrderResult.OrderID == "0000") { MessageBox.Show("未登录!"); } if (addOrderResult.OrderID == "1111") { MessageBox.Show("wcf服务报错!"); } if (addOrderResult.OrderID == "error") { MessageBox.Show("下单异常!"); } } } catch (Exception) { MessageBox.Show("访问HTTP服务器时出错!"); } }
/// <summary> /// Records a video using Emgu through the webcam and uploads it /// </summary> /// <param name="seconds">how many seconds to record for</param> /// <returns>url to the video file</returns> private string UploadVideoCapture(int seconds) { string path = FileHelper.GetTemporaryFilePath("MicrosoftTutorial.mp4"); VideoWriter writer = new VideoWriter(path, VideoWriter.Fourcc('M', 'P', '4', 'V'), 10, new Size(640, 480), true); // keep track of time during recording DateTime start = DateTime.Now; DateTime future; Capture capture = new Capture(); do { future = DateTime.Now; // write the frame writer.Write(capture.QueryFrame()); } while (DateTime.Compare(start.AddSeconds(seconds), future) > 0); // close the webcam connection writer.Dispose(); capture.Dispose(); string url = HTTPHelper.Upload(path); FileHelper.DeleteFile(path); return(url); }
private IEnumerable <HouseInfo> GetRoomList(int costFrom, int costTo, string cnName, int index) { var url = $"http://{cnName}.58.com/zufang/pn{index}/?isreal=true&minprice={costFrom}_{costTo}"; var htmlResult = HTTPHelper.GetHTMLByURL(url); var houseList = ParseRoom(htmlResult); return(houseList); }
private IEnumerable <HouseInfo> GetRoomListByIndex(string cnName, int index) { var url = $"http://{cnName}.58.com/zufang/pn{index}/?isreal=true"; var htmlResult = HTTPHelper.GetHTMLByURL(url); var houseList = ParseRoom(htmlResult); return(houseList); }
/// <summary> /// When exception occurs, log it to event log. /// </summary> /// <param name="eventCode">Code of event</param> /// <param name="errorTitle">Message to log to asynchronous log</param> /// <param name="ex">Exception to log</param> /// <param name="siteId">ID of site</param> private void LogExceptionToEventLog(string eventCode, string errorTitle, Exception ex, int siteId) { AddError(ResHelper.GetString(errorTitle, currentCulture) + ": " + ex.Message); LogContext.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", eventCode, currentUser.UserID, currentUser.UserName, 0, null, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), siteId, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent()); }