public void InitiateConnection(string url) { CrestronInvoke.BeginInvoke(o => { try { if (string.IsNullOrEmpty(url)) { Debug.Console(0, this, "Error connecting to Server. No URL specified"); return; } Client = new HttpClient(); Request = new HttpClientRequest(); Client.Verbose = true; Client.KeepAlive = true; Request.Url.Parse(url); Request.RequestType = RequestType.Get; Request.Header.SetHeaderValue("Accept", "text/event-stream"); // In order to get a handle on the response stream, we have to get // the request stream first. Boo Client.BeginGetRequestStream(GetRequestStreamCallback, Request, null); CrestronConsole.PrintLine("Request made!"); } catch (Exception e) { ErrorLog.Notice("Exception occured in AsyncWebPostHttps(): " + e.ToString()); } }); }
public void getWeather() { url = string.Format("http://api.wunderground.com/api/{0}/conditions/q/{1}.json", APIKey, ZipCode); try { var httpSet = new HttpClient(); httpSet.KeepAlive = false; httpSet.Accept = "text/html"; HttpClientRequest sRequest = new HttpClientRequest(); sRequest.Url.Parse(url); //send request URL HttpClientResponse sResponse = httpSet.Dispatch(sRequest); var jsontext = sResponse.ContentString; //dump info from request response into variable JObject Data = JObject.Parse(jsontext); RootObject myObject = JsonConvert.DeserializeObject <RootObject>(jsontext); //Reflection of JSON to myObject from class below ZipCode = myObject.current_observation.display_location.zip; //feed myObject data to SIMPL+ strings City = myObject.current_observation.display_location.city; Temp = myObject.current_observation.feelslike_string; Condition = myObject.current_observation.weather; ConditionURL = myObject.current_observation.icon_url; WindDirection = myObject.current_observation.wind_dir; WindSpeed = myObject.current_observation.wind_mph.ToString(); } catch (Exception e) { CrestronConsole.PrintLine("couldn't execute: {0}", e); } }
public string getFtFxFxmnSubmitOrder(string deviceId, string accountNo, string sessionID, string language, string product , string encryptedPIN, string authToken, string symbol, string exchange, string action, string orderType , string price, string qty, string expiry, string stopLimitPrice, string ocoType, string ocoPrice) { HttpClientRequest hcr = new HttpClientRequest(); hcr.headers.Clear(); hcr.headers.Add(new KeyValuePair <string, string>("deviceId", deviceId)); hcr.headers.Add(new KeyValuePair <string, string>("accountNo", accountNo)); hcr.headers.Add(new KeyValuePair <string, string>("sessionId", sessionID)); hcr.headers.Add(new KeyValuePair <string, string>("encryptedPIN", encryptedPIN)); hcr.headers.Add(new KeyValuePair <string, string>("authToken", authToken)); hcr.forms.Clear(); hcr.forms.Add(new KeyValuePair <string, string>("symbol", symbol)); hcr.forms.Add(new KeyValuePair <string, string>("exchange", exchange)); hcr.forms.Add(new KeyValuePair <string, string>("action", action)); hcr.forms.Add(new KeyValuePair <string, string>("orderType", orderType)); hcr.forms.Add(new KeyValuePair <string, string>("price", price)); hcr.forms.Add(new KeyValuePair <string, string>("qty", qty)); hcr.forms.Add(new KeyValuePair <string, string>("expiry", expiry)); hcr.forms.Add(new KeyValuePair <string, string>("stopLimitPrice", stopLimitPrice)); hcr.forms.Add(new KeyValuePair <string, string>("ocoType", ocoType)); hcr.forms.Add(new KeyValuePair <string, string>("ocoPrice", ocoPrice)); string path = string.Format(Commons.TRADE_FT_FX_FXMN_SUBMIT_PATH, product); string result = hcr.postRequest(path, hcr.headers, hcr.forms, language); ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); logger.Info(result + ""); return(result); }
private void buttonUpdateLine_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxLineId.Text)) { MessageBox.Show("Molimo odaberite liniju za izmjenu"); return; } Linije line = new Linije(); line.Id = Convert.ToInt32(textBoxLineId.Text); line.PolazakId = Convert.ToInt32(comboBoxStartLine.SelectedValue); usp_Get_All_Cities_Result destination = comboBoxDestinationLine.SelectedValue as usp_Get_All_Cities_Result; line.DestinacijaId = destination.Id; line.Naziv = comboBoxStartLine.Text + "-" + comboBoxDestinationLine.Text; line.PrevoznikId = Convert.ToInt32(comboBoxTravelers.SelectedValue); line.TipLinije = comboBoxTypeLine.Text; line.vrijemePolaska = dateTimePickerLine.Text; HttpResponseMessage response = HttpClientRequest.PostResult("/Relation/EditRelation", line); if (response.IsSuccessStatusCode) { MessageBox.Show("Uspjesno izmjenjena linija"); this.RelationForm_Load(sender, e); } }
public string getStocksSubmitOrder(string deviceId, string accountNo, string sessionID, string language , string authToken, string counterId, string action, string orderType, string limitPrice, string stopPrice, string quantity , string settlementCurrency, string payment, string triggerPriceType, string validity, string gtd) { HttpClientRequest hcr = new HttpClientRequest(); hcr.headers.Clear(); hcr.headers.Add(new KeyValuePair <string, string>("deviceId", deviceId)); hcr.headers.Add(new KeyValuePair <string, string>("accountNo", accountNo)); hcr.headers.Add(new KeyValuePair <string, string>("sessionId", sessionID)); hcr.headers.Add(new KeyValuePair <string, string>("authToken", authToken)); hcr.forms.Clear(); hcr.forms.Add(new KeyValuePair <string, string>("counterID", counterId)); hcr.forms.Add(new KeyValuePair <string, string>("action", action)); hcr.forms.Add(new KeyValuePair <string, string>("orderType", orderType)); hcr.forms.Add(new KeyValuePair <string, string>("limitPrice", limitPrice)); hcr.forms.Add(new KeyValuePair <string, string>("triggerPrice", stopPrice)); hcr.forms.Add(new KeyValuePair <string, string>("quantity", quantity)); hcr.forms.Add(new KeyValuePair <string, string>("settlementCurrency", settlementCurrency)); hcr.forms.Add(new KeyValuePair <string, string>("payment", payment)); hcr.forms.Add(new KeyValuePair <string, string>("triggerPriceType", triggerPriceType)); hcr.forms.Add(new KeyValuePair <string, string>("validity", validity)); hcr.forms.Add(new KeyValuePair <string, string>("gtd", gtd)); string result = hcr.postRequest(Commons.TRADE_STOCK_SUBMIT_PATH, hcr.headers, hcr.forms, language); ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); logger.Info(result + ""); return(result); }
/// <summary> /// <summary> /// 获取用户的openId /// <para>作 者:蔡亚康</para> /// <para>创建时间:2019-03-07</para> /// </summary> /// </summary> /// <param name="code">通过小程序获取到的用户登录凭证(有效期五分钟)。</param> /// <exception> /// 异常ID:4->OPENID获取失败 /// </exception> /// <returns></returns> public OpenIdResponse GetOpenId(string code) { OpenIdResponse result = null; try { HssConfig config = ClientConfigManager.HssConfig; Dictionary <string, string> paras = new Dictionary <string, string>(); paras.Add("appid", config.AppId); paras.Add("secret", config.AppSecret); paras.Add("js_code", code); paras.Add("grant_type", WxConfig.GRANT_TYPE); HttpClientRequest request = new HttpClientRequest(); result = request.Get <OpenIdResponse>(config.JsCode2SessionUrl, paras); if (result.ErrCode != WxConfig.RESULT_SUCCESS) { throw new BussinessException(ModelType.Hss, 4, result.ErrMsg); } } catch (Exception ex) { LogWriter.Write(this, ex.Message, LoggerType.Error); throw new BussinessException(ModelType.Hss, 4); } return(result); }
private void request(string url, string param, RequestType method) { if (param != "") { url = url + "?" + param; } HttpClient client = new HttpClient(); client.Verbose = false; HttpClientRequest request = new HttpClientRequest(); request.KeepAlive = true; request.Url.Parse(url); request.RequestType = method; client.DispatchAsync(request, (hscrs, e) => { try { if (hscrs.Code >= 200 && hscrs.Code < 300) { // success string s = hscrs.ContentString.ToString(); CrestronConsole.Print("Data: " + s + "\n"); if (OnRes != null) { OnRes(s); } } } catch (Exception f) { CrestronConsole.PrintLine("Connection error:::" + f.ToString()); } }); }
public void SetMethodName_BuildFor_MethodNameEquals() { var method = HttpMethod.Get; var request = HttpClientRequest.Create(method); Assert.AreEqual(method.Name, request.Method.Name); }
private HttpConnect() { _client = new HttpClient(); _client.KeepAlive = false; _client.Accept = "application/json"; _request = new HttpClientRequest(); }
/// <summary> /// 取消订单 /// </summary> public static void CancelOrder() { CancelOrderParam cancelOrderParam = new CancelOrderParam(); cancelOrderParam.tradeID = 214498786581086919;//213485383312086919 214228696119086919 cancelOrderParam.remark = "测试"; cancelOrderParam.cancelReason = "buyerCancel"; cancelOrderParam.RequestType = "CancelOrder"; cancelOrderParam.GetRequestUrl(); string url = cancelOrderParam.URL; string postData = string.Join("&", cancelOrderParam.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData); if (responseResult.Success) { //进行序列化 if (!string.IsNullOrEmpty(responseResult.Result)) { try { } catch (Exception ex) { string meg = ex.Message; } } } }
/// <summary> /// 下载订单 /// </summary> public static void UpLoadOrder() { GetOrderParam getOrderParam = new GetOrderParam(); getOrderParam.orderId = 229560749877086919; //209934924621086919,213485383312086919 getOrderParam.includeFields = "GuaranteesTerms,NativeLogistics,RateDetail,OrderInvoice,OrderBizInfo,baseInfo,productItems"; // getOrderParam.GetRequestUrl(); HttpClientRequest httpClient = new HttpClientRequest(); string postData = string.Join("&", getOrderParam.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); ResponseResult responseResult = httpClient.RequesResult(getOrderParam.URL, postData); if (responseResult.Success) { //进行序列化 if (!string.IsNullOrEmpty(responseResult.Result)) { try { GetOrdersResponse ordersResponse = JsonConvert.DeserializeObject <GetOrdersResponse>(responseResult.Result); if (ordersResponse != null) { } } catch (Exception ex) { string meg = ex.Message; } } } }
/// <summary> /// 刷新token /// </summary> public static void RefeshToken() { RefreshTokenParam refreshTokenParam = new RefreshTokenParam(); refreshTokenParam.GetRequestUrl(); string url = refreshTokenParam.URL; string postData = string.Join("&", refreshTokenParam.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData); if (responseResult.Success) { //进行序列化 if (!string.IsNullOrEmpty(responseResult.Result)) { try { } catch (Exception ex) { string meg = ex.Message; } } } }
/// <summary> /// 下载产品 /// </summary> public static void LoadProduct() { GetProductParam getProductParam = new GetProductParam(); getProductParam.productId = 547363119296;// 576620941437 565461451556 561577651929 554833936110 getProductParam.GetRequestUrl(); string url = getProductParam.URL; string postData = string.Join("&", getProductParam.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData); if (responseResult.Success) { //进行序列化 if (!string.IsNullOrEmpty(responseResult.Result)) { try { GetProductResponse productResponse = JsonConvert.DeserializeObject <GetProductResponse>(responseResult.Result); string productId = productResponse.productInfo.productID.ToString(); string staus = productResponse.productInfo.status; string subject = productResponse.productInfo.subject; string categoryName = productResponse.productInfo.categoryName; List <SkuInfos> skuInfosList = new List <SkuInfos>(); List <SkuInfos> list = productResponse.productInfo.skuInfos; } catch (Exception ex) { string meg = ex.Message; } } } }
// Notify() sends a POST request to the Subscription's callback URL. // DispatchAsync could be used to keep this method from blocking if the server has many subscriptions public void Notify() { try { HttpClientRequest req = new HttpClientRequest(); req.RequestType = RequestType.Post; // First, resolve the hostname using the ResolveHost method var parsedUrl = new UrlParser(SubscriberCallbackUrl); string resolvedHostname = ResolveHost(parsedUrl.Hostname); // Swap in the resolved hostname when setting the target URL of the notification string resolvedUrl = parsedUrl.ToString().Replace(parsedUrl.Hostname, resolvedHostname); req.Url = new UrlParser(resolvedUrl); HttpHeaders headers = new HttpHeaders(); headers.SetHeaderValue("Notification-Type", NotificationType); headers.SetHeaderValue("Link", "<" + ResourceUrl + ">, rel=\"Resource\""); req.Header = headers; req.FinalizeHeader(); HttpClientResponse res = notifier.Dispatch(req); if (res.Code != 200) { CrestronConsole.PrintLine("Notification to " + resolvedUrl + " not acknowledged"); } // Must call Dispose on the HttpClientResponse object to end the http session res.Dispose(); } catch (Exception e) { CrestronConsole.PrintLine(e.ToString()); } }
public string invokeRemoveCounter(string deviceId, string accountNo, string sessionID, string language, string watchlistId, string counterIDsString) { HttpClientRequest hcr = new HttpClientRequest(); hcr.headers.Clear(); hcr.headers.Add(new KeyValuePair <string, string>("deviceId", deviceId)); hcr.headers.Add(new KeyValuePair <string, string>("accountNo", accountNo)); hcr.headers.Add(new KeyValuePair <string, string>("sessionId", sessionID)); hcr.forms.Clear(); string[] counterIDs = counterIDsString.Split(','); for (int i = 0; i < counterIDs.Length; i++) { hcr.forms.Add(new KeyValuePair <string, string>("counterIDs", counterIDs[i])); } string path = Commons.WATCHLIST_REMOVE_COUNTER_PATH.Replace("?", watchlistId); string result = hcr.postRequest(path, hcr.headers, hcr.forms, language); ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); logger.Info(result + ""); return(result); }
public BonAppService(BonAppSetup setup) { this.setup = setup; // allow data caching to 20 min cache = new Utils.Cache <JsonValue>(200, TimeSpan.FromMinutes(20), async(string key) => { JsonValue res = null; var url = new Uri(setup.url); using (HttpClient client = await HttpClient.CreateAsync(url)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = key; request.Headers["menuapi-key"] = setup.apiKey; await client.SendRequestAsync(request); HttpClientResponse response = await client.GetResponseAsync(); if (response.StatusCode == 200) { res = await response.ReadAsJsonAsync(); } else { Console.WriteLine(await response.ReadAsStringAsync()); } } return(res); }); }
public static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: TestHttpClient.exe [URL]"); } else { Uri uri = new Uri(args[0]); using (HttpClient client = HttpClient.Create(uri.Host, uri.Port)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = uri.PathAndQuery; client.SendRequest(request); HttpClientResponse response = client.GetResponse(); Console.WriteLine(response.Protocol + " " + response.Status); foreach (string key in response.Headers.Keys) { Console.WriteLine(key + ": " + response.Headers[key]); } Console.WriteLine(); Console.WriteLine(response.ReadAsString()); } } }
/// <summary> /// 创建订单预览 /// </summary> public static void CreateOrderPreview() { CreateOrderPreviewParam createOrderPreviewParam = new CreateOrderPreviewParam(); // createOrderPreviewParam.invoiceParam = GetInvoiceParam(); createOrderPreviewParam.addressParam = GetAddressParam(); createOrderPreviewParam.cargoParamList = GetCargoParamList(); createOrderPreviewParam.GetRequestUrl(); string url = "https://gw.open.1688.com/openapi/param2/1/com.alibaba.trade/alibaba.createOrder.preview/6368408";// createOrderPreviewParam.URL; string postData = string.Join("&", createOrderPreviewParam.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData); if (responseResult.Success) { //进行序列化 if (!string.IsNullOrEmpty(responseResult.Result)) { try { CreateOrderPreviewResponse productResponse = JsonConvert.DeserializeObject <CreateOrderPreviewResponse>(responseResult.Result); } catch (Exception ex) { string meg = ex.Message; } } } }
HttpClientResponse Get(string path) { HttpClientRequest request = new HttpClientRequest(); request.Url = new UrlParser(string.Format("http://{0}:80{1}", this.Host, path.StartsWith("/") ? path : "/" + path)); return(this.Request(request)); }
/// <summary> /// 取消子账号授权 /// </summary> /// <param name="appAccount"></param> /// <param name="accountList"></param> /// <returns></returns> public static ResultModel <SubaccountAuthCancelResponse> SubaccountAuthCancel(List <string> accountList) { ResultModel <SubaccountAuthCancelResponse> resultModel = new ResultModel <SubaccountAuthCancelResponse>() { Success = true }; SubaccountAuthCancelParam subaccountAuthCancel = new SubaccountAuthCancelParam(); //获取子账号列表 subaccountAuthCancel.SubUserIdentityList = accountList; subaccountAuthCancel.GetRequestUrl(); string url = subaccountAuthCancel.URL; string postData = string.Join("&", subaccountAuthCancel.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData, subaccountAuthCancel.RequestType); if (responseResult.Success) { SubaccountAuthCancelResponse subaccountAuthResult = JsonConvert.DeserializeObject <SubaccountAuthCancelResponse>(responseResult.Result); resultModel.Result = subaccountAuthResult; } else { resultModel.Success = false; } return(resultModel); }
public void GetUriFor_queryIsEmpty_UriAbsoluteUrlEqualsHost() { var host = "http://www.ya.ru"; var uri = HttpClientRequest.CreateGet().GetUriFor(host); Assert.AreEqual(host + "/", uri.AbsoluteUri); }
public static ResultModel <SubaccountAuthResult> GetSubaccountAuthInfo() { //string encodedUrl = "%5B%22%E6%B7%B1%E5%9C%B3%E5%82%B2%E5%9F%BA2018%3Axs057%22%5D"; //string decodedUrl = HttpUtility.UrlDecode(encodedUrl); //encodedUrl = HttpUtility.UrlEncode(decodedUrl); ResultModel <SubaccountAuthResult> resultModel = new ResultModel <SubaccountAuthResult>() { Success = true }; GetSubaccountAuthInfoParam subaccountAuth = new GetSubaccountAuthInfoParam(); subaccountAuth.SubUserIdentityList = new List <string>() { "深圳傲基2018:ao504" }; subaccountAuth.GetRequestUrl(); string url = subaccountAuth.URL; // string postData = CreateParameterStr(subaccountAuth.m_DictParameters); string postData = string.Join("&", subaccountAuth.m_DictParameters.Select(zw => zw.Key + "=" + zw.Value)); HttpClientRequest httpClient = new HttpClientRequest(); ResponseResult responseResult = httpClient.RequesResult(url, postData); if (responseResult.Success) { SubaccountAuthResult subaccountAuthResult = JsonConvert.DeserializeObject <SubaccountAuthResult>(responseResult.Result); resultModel.Result = subaccountAuthResult; } else { resultModel.Success = false; } return(resultModel); }
private string SendToClient(string url) { try { var body = string.Empty; using (HttpClient client = new HttpClient()) { HttpClientRequest request = new HttpClientRequest(); client.TimeoutEnabled = true; client.Timeout = 25; client.Port = p; request.Url.Parse(url); request.Header.AddHeader(new HttpHeader("X-Plex-Client-Identifier", identifier)); request.Header.AddHeader(new HttpHeader("X-Plex-Target-Client-Identifier", identifier)); request.Header.AddHeader(new HttpHeader("X-Plex-Device-Name", "Crestron")); request.Header.AddHeader(new HttpHeader("Access-Control-Expose-Headers", "X-Plex-Client-Identifier")); HttpClientResponse response = client.Dispatch(request); body = response.ContentString; request = null; response.Dispose(); } return(body); } catch (Exception e) { e.ToString(); return(string.Empty); } }
/// <summary> /// SMS_46780073 非正常开门 您好,您的朋友${uname}正在使用非正常指纹回家,请妥善处理!!! /// </summary> /// <param name="name">名称</param> /// <param name="mobile">手机</param> public void SendUnLockMsg(string name, string mobile) { String querys = string.Format("ParamString={0}&RecNum={1}&SignName={2}&TemplateCode=SMS_48945056", HttpUtility.UrlEncode("{\"uname\":\"" + name + "\"}", System.Text.Encoding.UTF8), mobile, HttpUtility.UrlEncode("艾力智能", System.Text.Encoding.UTF8)); String url = "http://sms.market.alicloudapi.com/singleSendSms?" + querys; //ParamString%3d+%7b%22uname%22%3a%2213867911360%22%7d%26RecNum%3d13867911360%26SignName%3d%e8%89%be%e5%8a%9b%e9%9b%86%e6%88%90%26TemplateCode%3dSMS_46780073 Crestron.SimplSharp.Net.Http.HttpClient client = new Crestron.SimplSharp.Net.Http.HttpClient(); HttpClientRequest request = this.GetRequest(url); try { HttpClientResponse httpResponse = client.Dispatch(request); ILiveDebug.Instance.WriteLine("SMS:" + querys); httpResponse.Encoding = Encoding.UTF8; string html = httpResponse.ContentString; ILiveDebug.Instance.WriteLine(html); } catch (Exception ex) { ILiveDebug.Instance.WriteLine("ex:" + ex.Message); } }
// Unsubscribe to the relay on the server control system public void Unsubscribe() { try { if (!subscribed) { CrestronConsole.PrintLine("Already unsubscribed to relay on " + serverAPIUrl); return; } // send a DELETE request to the subscription URL HttpClientRequest req = new HttpClientRequest(); req.Url = subscriptionUrl; req.RequestType = RequestType.Delete; HttpClientResponse res = client.Dispatch(req); if (res.Code == 204) // Expecting a "Not Found" response to show that the DELETE succeeded { CrestronConsole.PrintLine("Deleted subscription to relay " + rlyID); subscribed = false; } else { CrestronConsole.PrintLine("Server was unable to delete subscription to relay " + rlyID); } res.Dispose(); } catch (Exception e) { CrestronConsole.PrintLine("Error in Unsubscribe: " + e.Message); } }
public string getCounterPrices(string deviceId, string accountNo, string sessionID, string language, string size, string counterIDsString) { HttpClientRequest hcr = new HttpClientRequest(); hcr.headers.Clear(); hcr.headers.Add(new KeyValuePair <string, string>("deviceId", deviceId)); hcr.headers.Add(new KeyValuePair <string, string>("accountNo", accountNo)); hcr.headers.Add(new KeyValuePair <string, string>("sessionId", sessionID)); //string param = "&size=" + size + "&counterIDs=" + counterIDs; string[] counterIDs = counterIDsString.Split(','); string param = "&size=" + counterIDs.Length; for (int i = 0; i < counterIDs.Length; i++) { //hcr.forms.Add(new KeyValuePair<string, string>("counterIDs", counterIDs[i])); param += "&counterIDs=" + counterIDs[i]; } string result = hcr.getRequest(Commons.COUNTER_PRICELIST_PATH, hcr.headers, param, language); ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); logger.Info(result + ""); return(result); }
/// <exception cref="InvalidDataException"></exception> private AsyncRequest CreateRequest(HttpClientRequest request) { byte[] data; var webRequest = CreateRequest(request, out data); return(new AsyncRequest(webRequest, data)); }
public void AsyncRequestThrowsAfterTimeout_AsyncRequestAbortCalled() { var sender = new HttpSenderAsync("ya.ru", new IContentEncoder[0]); var requestStub = HttpClientRequest.CreateJsonPost("content").SetTimeout(TimeSpan.Zero); var resetEvent = new ManualResetEventSlim(false); Exception catchedException = null; sender.UnderlyingAsyncExceptionHandler += (e) => catchedException = e; Func <HttpWebResponse> waitForEvent = () => { resetEvent.Wait(); return(null); }; var mock = new Mock <ITinyAsyncRequest>(); mock.Setup(s => s.Send()).Returns(() => Task.Run(waitForEvent)); mock.Setup(s => s.Abort()); sender.AsyncRequestFactory = (r, d) => mock.Object; //Send with zero timeout Assert.Throws <TinyTimeoutException>(() => sender.Send(requestStub)); mock.Verify(m => m.Abort(), Times.Once); //unblock async request resetEvent.Set(); }
async Task <XDocument> LoadXmlAsync(Uri url, int maxRedirect = 5) { using (var client = await HttpClient.CreateAsync(url, 5000, 10000)) { var clientRequest = new HttpClientRequest { Method = "GET", Path = url.PathAndQuery }; await client.SendRequestAsync(clientRequest); var response = await client.GetResponseAsync(); if ((response.StatusCode == 301 || response.StatusCode == 302) && response.Headers.ContainsKey("location")) { if (maxRedirect <= 0) { logger.Log(LogLevel.Error, $"While loading '{url}' got too many HTTP REDIRECT"); return(null); } var redirectUrl = new Uri(url, response.Headers["location"]); return(await LoadXmlAsync(redirectUrl, maxRedirect - 1)); } if (response.StatusCode == 200) { return(XDocument.Load(response.InputStream)); } logger.Log(LogLevel.Error, $"While loading '{url}' got HTTP {response.StatusCode}"); } return(null); }
public string getUtSubmitOrder(string deviceId, string accountNo, string sessionID, string language, string encryptedPIN , string counterId, string action, string fundSource, string paymentCurrency, string invAmount, string unit , string switchInID, string emailNotification, string declaration, string termCondition) { HttpClientRequest hcr = new HttpClientRequest(); hcr.headers.Clear(); hcr.headers.Add(new KeyValuePair <string, string>("deviceId", deviceId)); hcr.headers.Add(new KeyValuePair <string, string>("accountNo", accountNo)); hcr.headers.Add(new KeyValuePair <string, string>("sessionId", sessionID)); hcr.headers.Add(new KeyValuePair <string, string>("encryptedPIN", encryptedPIN)); hcr.forms.Clear(); hcr.forms.Add(new KeyValuePair <string, string>("counterID", counterId)); hcr.forms.Add(new KeyValuePair <string, string>("action", action)); hcr.forms.Add(new KeyValuePair <string, string>("fundSource", fundSource)); hcr.forms.Add(new KeyValuePair <string, string>("paymentCurrency", paymentCurrency)); hcr.forms.Add(new KeyValuePair <string, string>("invAmount", invAmount)); hcr.forms.Add(new KeyValuePair <string, string>("unit", unit)); hcr.forms.Add(new KeyValuePair <string, string>("switchInID", switchInID)); hcr.forms.Add(new KeyValuePair <string, string>("emailNotification", emailNotification)); hcr.forms.Add(new KeyValuePair <string, string>("declaration", declaration)); hcr.forms.Add(new KeyValuePair <string, string>("termCondition", termCondition)); string result = hcr.postRequest(Commons.TRADE_UT_SUBMIT_PATH, hcr.headers, hcr.forms, language); ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); logger.Info(result + ""); return(result); }
public Configuration GetConfiguration() { var address = baseAddress + "configuration" + APIKEY; var uri = new Uri(address); var request = new HttpClientRequest<Configuration>(); return request.GetRequest(uri); }
public MovieSearch SearchMovies(string movieQuery) { var address = baseAddress + "search/movie" + APIKEY + "&query=" + movieQuery; var uri = new Uri(address); var request = new HttpClientRequest<MovieSearch>(); return request.GetRequest(uri); }
public void Authenticate() { HttpClient client = new HttpClient(); //client.Verbose = false; //Testing //client.AllowAutoRedirect = true; HttpClientRequest request = new HttpClientRequest(); HttpClientResponse response; String url = "http://checkip.dyndns.org"; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Http.RequestType.Get; try { response = client.Dispatch(request); } catch(Exception e) { ErrorLog.Error("**Failed To Retrieve External IP Address**\n"); ErrorLog.Error("Verify Internet Connection and Try Again\n"); response = null; return; } string pattern = @".*?\: (.*?)<\/body>"; var r = new Regex(pattern, RegexOptions.IgnoreCase); if (response.ContentString != null) { var match = r.Match(response.ContentString); if (match.Success) { SmartThingsReceiver.IP = match.Groups[1].Value; ErrorLog.Notice("Please Copy and Paste the Following URL into your browser to continue\n"); ErrorLog.Notice("https://graph.api.smartthings.com/oauth/authorize?response_type=code&client_id=" + ClientID + "&redirect_uri=http://" + IP + ":" + Port.ToString() + "&scope=app"); } else ErrorLog.Notice("{0}\n", response.ContentString); } }
public void PollData() { baseURL = "http://" + myIPAddress + ":" + port + "/data_request?id=sdata"; myHttpClient.Url.Parse(baseURL); try { if (!myHttpClient.ProcessBusy) { HttpClientRequest myHttpRequest = new HttpClientRequest(); myHttpRequest.Url.Parse(baseURL); myHttpRequest.RequestType = RequestType.Get; HttpClientResponse myHttpResponse = myHttpClient.Dispatch(myHttpRequest); //CrestronConsole.PrintLine(myHttpResponse.ContentString); RootObject jobj = JsonConvert.DeserializeObject<RootObject>(myHttpResponse.ContentString); myHttpClient.Abort(); CrestronConsole.PrintLine("Database:" + jobj.dataversion); /*foreach (var item in jobj.rooms) { CrestronConsole.PrintLine("Room:{0}, Name:{1} Section:{2}", item.id,item.name,item.section); } foreach (var ItemScene in jobj.scenes) { CrestronConsole.PrintLine("SceneName:{0}, ID:{1} Active:{2} RoomNr:{3}", ItemScene.name,ItemScene.id,ItemScene.active,ItemScene.room); } foreach (var ItemCategories in jobj.categories) { CrestronConsole.PrintLine("CatName:{0}, ID:{1}", ItemCategories.name,ItemCategories.id); } foreach (var ItemDevice in jobj.devices.Where(ItemDevice => ItemDevice.category == 17)) { CrestronConsole.PrintLine("Temerature:{0} RoomID:{1}", ItemDevice.temperature,ItemDevice.room); } foreach (var ItemDevice in jobj.devices.Where(ItemDevice => ItemDevice.category == 18)) { CrestronConsole.PrintLine("Lights:{0} RoomID:{1}", ItemDevice.light, ItemDevice.room); } */ foreach (var ItemDevice in jobj.devices.Where(ItemDevice => ItemDevice.category == 3)) { CrestronConsole.PrintLine("Rom:{2} Name:{0} Status:{1} Watts:{3}", ItemDevice.name, ItemDevice.status,ItemDevice.room, ItemDevice.watts); } //CrestronConsole.PrintLine(" Xx:-)"); } else { CrestronConsole.PrintLine("ProcessBusy!"); } } catch (Exception ex) { myHttpClient.Abort(); CrestronConsole.PrintLine("Error sending commandX: {0} ", ex.Message); if (OnError != null) OnError(new SimplSharpString(ex.ToString() + "\new\ref" + ex.StackTrace)); } }