Пример #1
0
        private string GetSignature(string endpoint, List <KeyValuePair <string, string> > data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            data.Sort(CompareKeyValuePair);
            using (var content = new FormUrlEncodedContent(data))
            {
                var queryString = WebUtility.UrlDecode(content.ReadAsStringAsync().Result);
                var plainString = $"GET{endpoint}{Uri}?{queryString}";

                using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(SecretKey)))
                {
                    return(Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(plainString))));
                }
            }
        }
        public async Task TrackEvent(string cid, string eventCategory, string eventAction, string eventLabel)
        {
            var payload = new FormUrlEncodedContent(new[] {
                KeyValuePair.Create("v", "1"),
                KeyValuePair.Create("tid", tid),
                KeyValuePair.Create("cid", cid),
                KeyValuePair.Create("t", "event"),
                KeyValuePair.Create("ec", eventCategory),
                KeyValuePair.Create("ea", eventAction),
                KeyValuePair.Create("el", eventLabel)
            });

            var payloadString = await payload.ReadAsStringAsync();

            var res = await httpClient.PostAsync(
                new System.Uri("https://www.google-analytics.com/collect"),
                new StringContent(payloadString));
        }
Пример #3
0
        private (string, IHeaderDictionary) FormRequest(object request, string endpoint, string token = null)
        {
            var headers = new HeaderDictionary();

            var properties = request.GetType()
                             .GetRuntimeFields()
                             .Where(p => p.GetValue(request) != null).Select(p => new { p.Name, Value = p.GetValue(request) })
                             .ToDictionary(d => d.Name, v => v.Value.ToString());

            properties.Add("ticket", token ?? Ticket);

            using (var encodedContent = new FormUrlEncodedContent(properties))
            {
                var requestString = $"{tccBaseUrl}/tcc/{endpoint}?" + encodedContent.ReadAsStringAsync().Result;

                return(requestString, headers);
            }
        }
Пример #4
0
        /// <summary>
        /// Retorna uma QueryString baseada nas propriedades do objeto informado.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static async Task <string> ToQueryStringAsync(this object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            IDictionary <string, string> keyValueContent = obj.ToDictionary();

            if (keyValueContent == null)
            {
                return(null);
            }

            var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);

            return(await formUrlEncodedContent.ReadAsStringAsync());
        }
Пример #5
0
        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="instrument_id">币对</param>
        /// <param name="order_id">订单ID</param>
        /// <returns></returns>
        public async Task <JObject> getOrderByIdAsync(string instrument_id, string order_id)
        {
            var url = $"{this.BASEURL}{this.SPOT_SEGMENT}/orders/{order_id}";

            using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, null)))
            {
                var queryParams = new Dictionary <string, string>();
                queryParams.Add("instrument_id", instrument_id);
                var encodedContent = new FormUrlEncodedContent(queryParams);
                var paramsStr      = await encodedContent.ReadAsStringAsync();

                var res = await client.GetAsync($"{url}?{paramsStr}");

                var contentStr = await res.Content.ReadAsStringAsync();

                return(JObject.Parse(contentStr));
            }
        }
Пример #6
0
        public static async Task <IEnumerable <Claim> > GetTokenAsync(string username, string password)
        {
            using (var client = new HttpClient(new HttpClientHandler(), false))
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("username", username),
                    new KeyValuePair <string, string>("password", password),
                    new KeyValuePair <string, string>("grant_type", "password")
                });

                var response = await client.PostAsync(_tokenUri, content, new CancellationToken()).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    var responseToken = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    var json = JObject.Parse(responseToken);
                    var jwt  = json["access_token"].ToString();

                    JwtSecurityTokenHandler handler;
                    JwtSecurityToken        jwtTokenContent;

                    try
                    {
                        handler         = new JwtSecurityTokenHandler();
                        jwtTokenContent = handler.ReadToken(jwt) as JwtSecurityToken;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    return(jwtTokenContent.Claims);
                }
                else
                {
                    var errorResponse = await content.ReadAsStringAsync().ConfigureAwait(false);

                    throw new HttpException((int)HttpStatusCode.InternalServerError, errorResponse);
                }
            }
        }
Пример #7
0
        private static async Task <string> GetSign(Dictionary <string, string> form = null)
        {
            form = form ?? new Dictionary <string, string>();

            var content     = new FormUrlEncodedContent(form);
            var encodedForm = await content.ReadAsStringAsync();


            var encoding  = new UTF8Encoding();
            var keyBytes  = encoding.GetBytes(APIKeys.SECRET);
            var formBytes = encoding.GetBytes(encodedForm);

            var sha512    = new HMACSHA512(keyBytes);
            var hashBytes = sha512.ComputeHash(formBytes);

            var sign = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();

            return(sign);
        }
Пример #8
0
        /// <summary>
        /// Gets Percentage of occupied space
        /// </summary>
        public async Task <ResponseModel> GetPercentageofOccupiedSpace(int userId)
        {
            // double
            CheckJwt();
            UriBuilder ub = new UriBuilder(rootUrl + "/api/parking/getpercentageofoccupiedspace");

            using (var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "userId", userId.ToString() }
            }))
            {
                ub.Query = await content.ReadAsStringAsync();
            }
            HttpResponseMessage response = await client.GetAsync(ub.Uri);

            string resultString = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ResponseModel>(resultString));
        }
Пример #9
0
        /// <summary>
        /// Calculates remaining parking cost
        /// </summary>
        public async Task <ResponseModel> GetRemainingCost(int ticketNumber)
        {
            // decimal
            CheckJwt();
            UriBuilder ub = new UriBuilder(rootUrl + "/api/parking/getremainingcost");

            using (var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "userName", CurrentUser.Username }
            }))
            {
                ub.Query = await content.ReadAsStringAsync();
            }
            HttpResponseMessage response = await client.GetAsync(ub.Uri);

            string resultString = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ResponseModel>(resultString));
        }
Пример #10
0
        public async Task <IActionResult> Login()
        {
            var pkce = new Pkce
            {
                // uses the IdentityModel NuGet package to create a strongly random URL safe identifier
                // this will be our Code Verifier
                CodeVerifier = CryptoRandom.CreateUniqueId(32)
            };

            using (var sha256 = SHA256.Create())
            {
                // Here we create a hash of the code verifier
                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(pkce.CodeVerifier));

                // and produce the "Code Challenge"  from it by base64Url encoding it.
                pkce.CodeChallenge = Base64Url.Encode(challengeBytes);
            }

            // Save the CodeVerifier in the memorycache so we are able to use it later
            // This is just for demonstration. Please consider saving this in a more robust solution.
            _memoryCache.Set(AppConstants.PKCECacheKey, pkce);

            // Build the authorize url
            var authorizeArgs = new Dictionary <string, string>
            {
                { "client_id", _appConfiguration.ClientId },
                { "scope", "read:core:entities read:owneraccounts offline_access" },
                { "redirect_uri", "http://localhost:55183/Auth/LoginCallback" },
                { "response_type", "code" },

                // Provide the Code Challenge along with the method (Sha256)
                { "code_challenge", pkce.CodeChallenge },
                { "code_challenge_method", "S256" }
            };

            var content         = new FormUrlEncodedContent(authorizeArgs);
            var contentAsString = await content.ReadAsStringAsync();

            // prepare the URL for the authorize endpoint
            var url = $"{_appConfiguration.TapkeyAuthorizationServerUrl}/{_appConfiguration.TapkeyAuthorizationEndpointPath}?{contentAsString}";

            return(Redirect(url));
        }
Пример #11
0
        public async System.Threading.Tasks.Task CreateAsynchronousSignature()
        {
            var client   = new HttpClient();
            var postData = new List <KeyValuePair <string, string> >();

            //postData.Add(new KeyValuePair<string, string>("Name", "Grace Hopper"));
            postData.Add(new KeyValuePair <string, string>("request", "{\"dataHash\": {\"algorithm\": \"SHA-256\",\"value\": \"GHgonhozPdhQkdMPABufb57U1CjVfgSb0OvU28ib0hA=\"  },  \"level\": 0,  \"metadata\": { }        }"));

            var    formContent    = new FormUrlEncodedContent(postData);
            string requestContent = await formContent.ReadAsStringAsync();

            var response = await client.PostAsync("https://tryout-catena-db.guardtime.net/api/v1/signatures", formContent);

            var content = await response.Content.ReadAsStringAsync();

            //Assert.That(response.IsSuccessStatusCode);
            //Debug.WriteLine(message: "Request:" + requestContent);
            //Debug.WriteLine(message: "Response:" + content.ToString());
        }
        /// <inheritdoc/>
        public override Task <ISharedGroupFileInfo> GetFileInfoAsync(long groupNumber, string?id, bool fetchDownloadInfo, CancellationToken token = default)
        {
            InternalSessionInfo session = SafeGetSession();

            CreateLinkedUserSessionToken(session.Token, token, out CancellationTokenSource? cts, out token);
            KeyValuePair <string?, string?>[] payload = new KeyValuePair <string?, string?>[4]
            {
                new KeyValuePair <string?, string?>("sessionKey", session.SessionKey),
                new KeyValuePair <string?, string?>("id", id ?? null),
                new KeyValuePair <string?, string?>("target", groupNumber.ToString()),
                new KeyValuePair <string?, string?>("withDownloadInfo", fetchDownloadInfo.ToString().ToLower()),
            };
            using HttpContent content = new FormUrlEncodedContent(payload);
            string query = content.ReadAsStringAsync().GetAwaiter().GetResult();

            return(_client.GetAsync($"{_options.BaseUrl}/file/info?{query}", token)
                   .AsApiRespV2Async <ISharedGroupFileInfo, GroupFileInfo>(token)
                   .DisposeWhenCompleted(cts));
        }
        public async Task <Result <OutputObject> > Convert(InputObject inputObject)
        {
            HttpClient httpClient = new HttpClient();

            IEnumerable <KeyValuePair <string, string> > queryParameters = GetQueryParameters(inputObject);

            FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(queryParameters);

            UriBuilder uriBuilder = new UriBuilder(ApiBaseUri)
            {
                Query = await formUrlEncodedContent.ReadAsStringAsync()
            };

            HttpResponseMessage response = await httpClient.GetAsync(uriBuilder.Uri);

            return(response.IsSuccessStatusCode
                ? Result.Ok(await GetFromContentAsync(response.Content, inputObject))
                : Result.Failure <OutputObject>($"HTTP Error: {response.StatusCode}"));
        }
Пример #14
0
        /// <summary>
        /// Returns All Past Sessions if user is owner
        /// </summary>
        public async Task <ResponseModel> GetPastSesstionsForOwner(int userId)
        {
            // IEnumerable<ParkingSession>
            CheckJwt();
            UriBuilder ub = new UriBuilder(rootUrl + "/api/parking/getpastsesstionsforowner");

            using (var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "userId", userId.ToString() }
            }))
            {
                ub.Query = await content.ReadAsStringAsync();
            }
            HttpResponseMessage response = await client.GetAsync(ub.Uri);

            string resultString = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ResponseModel>(resultString));
        }
Пример #15
0
        public async void SendMsg(string content)
        {
            await RefreshChatList();

            foreach (string id in chatIDList)
            {
                var url = $"{this.TelegramUrl}/{this.TokenStr}/sendmessage";
                using (var client = new HttpClient())
                {
                    var queryParams = new Dictionary <string, string>();
                    queryParams.Add("chat_id", id);
                    queryParams.Add("text", content);
                    var encodedContent = new FormUrlEncodedContent(queryParams);
                    var paramsStr      = await encodedContent.ReadAsStringAsync();

                    var res = await client.GetAsync($"{url}?{paramsStr}");
                }
            }
        }
Пример #16
0
        public async Task <CurrentWeatherDto> FindForCoordinatesAsync(double latitude, double longitude, string units = "", CancellationTokenSource cancellationTokenSource = default(CancellationTokenSource))
        {
            if (latitude == -1 && longitude == -1)
            {
                return(null);
            }

            if (cancellationTokenSource == null)
            {
                cancellationTokenSource = new CancellationTokenSource();
            }

            string query;

            var result = new List <KeyValuePair <string, string> >();

            result.Add(new KeyValuePair <string, string>("lat", latitude.ToString()));
            result.Add(new KeyValuePair <string, string>("lon", longitude.ToString()));
            if (!string.IsNullOrEmpty(units))
            {
                result.Add(new KeyValuePair <string, string>("units", units));
            }
            result.Add(new KeyValuePair <string, string>("appid", ApiConstants.WeatherApiKey));

            using (var content = new FormUrlEncodedContent(result.ToArray()))
            {
                query = await content.ReadAsStringAsync();
            }

            var weather = await HttpProxy.Instance.GetAsync(Endpoint + "?" + query, cancellationTokenSource.Token);

            var possibleErrorResponse = JsonConvert.DeserializeObject <ErrorResponse>(weather);

            if (possibleErrorResponse.cod == 404)
            {
                return(null);
            }

            var weatherEntity = JsonConvert.DeserializeObject <CurrentWeather>(weather);

            return(new CurrentWeatherDto(weatherEntity));
        }
Пример #17
0
        /// <summary>
        /// submit this form, using a specified HttpClient.
        /// </summary>
        /// <remarks>
        /// the request will be set up from the form values.
        /// You can set up other options (like user-agent, timeout, cookies) before executing.
        /// </remarks>
        /// <returns>an async task.</returns>
        /// <exception cref="System.ArgumentException">
        /// if the form's absolute action URL cannot be determined.
        /// Make sure you pass the document's base URI when parsing.
        /// </exception>
        public Task <HttpResponseMessage> SubmitAsync(HttpClient client, CancellationToken cancellationToken)
        {
            string action = HasAttr("action") ? AbsUrl("action") : BaseUri;

            Validate.NotEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.");
            var data = new FormUrlEncodedContent(this.FormData);

            if (string.Equals(Attr("method"), "POST", StringComparison.OrdinalIgnoreCase))
            {
                // POST
                return(client.PostAsync(action, data, cancellationToken));
            }
            else
            {
                // GET
                var actionUrl = new UriBuilder(action);
                actionUrl.Query = data.ReadAsStringAsync().Result;
                return(client.GetAsync(actionUrl.Uri, cancellationToken));
            }
        }
Пример #18
0
        public async Task PostFormUrlEncodedContentAsyncWrapperTout_WhenCalled_UseCorrectMessageContent()
        {
            string sentContent = default;
            var    testContent = new Dictionary <string, string> {
                ["test"] = "test"
            };
            var expectedContent = new FormUrlEncodedContent(testContent);

            _moqHttpClientHandler.Protected().As <IHttpClientHandlerProtectedMembers>()
            .Setup(handler => handler.SendAsync(It.IsAny <HttpRequestMessage>(), It.IsAny <CancellationToken>()))
            .Returns <HttpRequestMessage, CancellationToken>(async(message, token) =>
            {
                sentContent = await message.Content.ReadAsStringAsync();
                return(_defaultResponce);
            });

            var result = await _requestWrapper.PostFormUrlEncodedContentAsyncWrapper <TestModelClass>(testContent, _testEndpoing);

            Assert.AreEqual(await expectedContent.ReadAsStringAsync(), sentContent);
        }
        private string CreateQueryString(List <DateTime> dates, string targetCurrency,
                                         string baseCurrency)
        {
            string queryString = "";

            List <DateTime> datesForRequest = SetRequestStartEndDates(dates);

            using (var content = new FormUrlEncodedContent(new Dictionary <string, string>()
            {
                { "start_at", DateTimeUtil.DateTimeToDateString(datesForRequest[0]) },
                { "end_at", DateTimeUtil.DateTimeToDateString(datesForRequest[datesForRequest.Count - 1]) },
                { "symbols", $"{targetCurrency}" },
                { "base", $"{baseCurrency}" }
            }))
            {
                queryString = baseUri + content.ReadAsStringAsync().Result;
            }

            return(queryString);
        }
Пример #20
0
        public async Task <NaomiResult> GetSearchResults(string file, NaomiOptions options = null)
        {
            if (!Uri.IsWellFormedUriString(file, UriKind.Absolute))
            {
                throw new ArgumentException("File URI is not well-formed.");
            }

            options = options ?? NaomiOptions.Default;

            var    qDict = options.BuildContent(file, ApiKey);
            string query;

            using (var content = new FormUrlEncodedContent(qDict.ToDictionary(k => k.Key, k => k.Value.ToString())))
            {
                query = content.ReadAsStringAsync().Result;
                string response = await Http.GetStringAsync("search.php?" + query);

                return(JsonConvert.DeserializeObject <NaomiResult>(response));
            }
        }
Пример #21
0
        public async Task DeleteStaff(string staffId)
        {
            var data = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("id", staffId)
            });

            var query = data.ReadAsStringAsync().Result;

            using (HttpResponseMessage response = await apiHelper.ApiClient.PostAsync("api/admin/delete?" + query, null))
            {
                if (response.IsSuccessStatusCode)
                {
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
Пример #22
0
        async Task <string> prepareUrlParameters(string url, Dictionary <string, string> parameters)
        {
            string requestUri;

            if (parameters != null)
            {
                using (var encodedParams = new FormUrlEncodedContent(parameters))
                {
                    var value = await encodedParams.ReadAsStringAsync();

                    requestUri = string.Format("{0}?{1}", url, value);
                }
            }
            else
            {
                requestUri = url;
            }

            return(requestUri);
        }
Пример #23
0
        private async Task <Uri> RenderUriAsync(string uri, object queryString = null, bool websocket = false)
        {
            if (queryString != null)
            {
                var keyValueContent       = ToKeyValue(queryString);
                var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                var urlEncodedString      = await formUrlEncodedContent.ReadAsStringAsync();

                uri += "?" + urlEncodedString;
            }

            return(new Uri(
                       websocket
                ? new Uri(BaseURL.ToString()   // there's got to be a cleaner way to do this...
                          .Replace("http://", "ws://")
                          .Replace("https://", "wss://"))
                : BaseURL,
                       uri
                       ));
        }
Пример #24
0
        public static string InitializeParamsQueryForClient(string origin, string destination, string departureDate, string returnDate, string adults, string currency)
        {
            //origin = "NYC";
            //destination = "MAD";

            DateTime departureDateDateTime = Convert.ToDateTime(departureDate);

            departureDate = departureDateDateTime.ToString("yyyy-MM-dd");

            if (!String.IsNullOrEmpty(returnDate))
            {
                DateTime returnDateDateTime = Convert.ToDateTime(returnDate);
                returnDate = departureDateDateTime.ToString("yyyy-MM-dd");
            }

            //adults = "5";
            //currency = "USD";

            var paramsDictionary = new Dictionary <string, string>();

            paramsDictionary.Add(Origin, origin);
            paramsDictionary.Add(Destination, destination);
            paramsDictionary.Add(DepartureDate, departureDate);
            if (!String.IsNullOrEmpty(returnDate))
            {
                paramsDictionary.Add(ReturnDate, returnDate);
            }
            paramsDictionary.Add(Adults, adults);
            if (!String.IsNullOrEmpty(currency))
            {
                paramsDictionary.Add(Currency, currency);
            }
            //paramsDictionary.Add(MaxOffers, ConfigurationManager.AppSettings[MaxOffers]);

            var paramsUrlEncoded = new FormUrlEncodedContent(paramsDictionary);
            var paramsQuery      = paramsUrlEncoded.ReadAsStringAsync().Result;

            paramsQuery = paramsQuery.Insert(0, "?");

            return(paramsQuery);
        }
Пример #25
0
        /// <summary>
        /// Pobranie danych tokena autoryzującego, używane przy logowaniu
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Hasło</param>
        /// <returns>Dictionary zawierający dane tokena</returns>
        public Dictionary <string, string> GetToken(string login, string password)
        {
            HttpContent content = new FormUrlEncodedContent(new Dictionary <string, string>()
            {
                { "grant_type", "password" },
                { "username", login },
                { "password", password }
            });

            try
            {
                using (HttpResponseMessage responseMessage = Task.Run(async() => { return(await _httpClient.PostAsync("Token", content)); }).Result)
                {
                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        content = responseMessage.Content;
                        string jsonString = Task.Run(async() => { return(await content.ReadAsStringAsync()); }).Result;
                        Dictionary <string, string> tokenData = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonString);
                        return(tokenData);
                    }
                    else if (responseMessage.StatusCode == HttpStatusCode.BadRequest)
                    {
                        _lastErrorMessage = "Niepoprawne dane logowania";
                    }
                    else
                    {
                        _lastErrorMessage = "Błąd połączenia z serwerem";
                    }
                }
            }
            catch (Exception exc)
            {
                _lastErrorMessage = "Błąd połączenia z serwerem";
            }
            finally
            {
                content.Dispose();
            }

            return(null);
        }
Пример #26
0
 // Throws on timeouts and server errors. Never returns null.
 string SendRequest(HttpMethod method, string relativeUri, IEnumerable <KV> param)
 {
     if (param.Any())
     {
         _log.Info("OUT: {0} {1} {{{2}}}", method.ToString().ToUpper(), relativeUri,
                   String.Join(", ", param.Select(kv => String.Format("{0}={1}", kv.Key, kv.Value))));
     }
     else
     {
         _log.Info("OUT: {0} {1}", method.ToString().ToUpper(), relativeUri);
     }
     try
     {
         var form = new FormUrlEncodedContent(param);
         var req  = new HttpRequestMessage();
         req.Method = method;
         if (method == HttpMethod.Get)
         {
             string query = form.ReadAsStringAsync().Result;
             if (query.Length > 0)
             {
                 Condition.Requires(relativeUri, "relativeUri").DoesNotContain("?").DoesNotContain("#");
                 relativeUri = String.Format("{0}?{1}", relativeUri, query);
             }
         }
         else if (method == HttpMethod.Post)
         {
             req.Content = form;
         }
         req.RequestUri = new Uri(relativeUri, UriKind.Relative);
         HttpResponseMessage resp = _http.SendAsync(req, HttpCompletionOption.ResponseContentRead).Result;
         string content           = resp.EnsureSuccessStatusCode().Content.ReadAsStringAsync().Result;
         _log.Info("IN: {0}", content);
         return(content);
     }
     catch (Exception e)
     {
         _log.Warn(e, "IO error");
         throw;
     }
 }
Пример #27
0
        /// <summary>
        /// 账单流水查询
        /// </summary>
        /// <param name="currency">币种,如btc</param>
        /// <param name="type">填写相应数字:1:充值2:提现13:撤销提现18:转入合约账户19:合约账户转出20:转入子账户21:子账户转出28:领取29:转入指数交易区30:指数交易区转出 31:转入点对点账户32:点对点账户转出 33:转入币币杠杆账户 34:币币杠杆账户转出 37:转入币币账户 38:币币账户转出</param>
        /// <param name="from">请求此页码之后的分页内容(举例页码为:1,2,3,4,5。from 4 只返回第5页,to 4只返回第3页)</param>
        /// <param name="to">请求此页码之前的分页内容(举例页码为:1,2,3,4,5。from 4 只返回第5页,to 4只返回第3页)</param>
        /// <param name="limit">分页返回的结果集数量,默认为100,最大为100,按时间顺序排列,越早下单的在前面</param>
        /// <returns></returns>
        public async Task <JContainer> getLedgerAsync(string currency, string type, int?from, int?to, int?limit)
        {
            var url = $"{this.BASEURL}{this.ACCOUNT_SEGMENT}/ledger";

            using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, null)))
            {
                var queryParams = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(currency))
                {
                    queryParams.Add("currency", currency);
                }
                if (!string.IsNullOrEmpty(type))
                {
                    queryParams.Add("type", type);
                }
                if (from.HasValue)
                {
                    queryParams.Add("from", from.Value.ToString());
                }
                if (to.HasValue)
                {
                    queryParams.Add("to", to.Value.ToString());
                }
                if (limit.HasValue)
                {
                    queryParams.Add("limit", limit.Value.ToString());
                }
                var encodedContent = new FormUrlEncodedContent(queryParams);
                var paramsStr      = await encodedContent.ReadAsStringAsync();

                var res = await client.GetAsync($"{url}?{paramsStr}");

                var contentStr = await res.Content.ReadAsStringAsync();

                if (contentStr[0] == '[')
                {
                    return(JArray.Parse(contentStr));
                }
                return(JObject.Parse(contentStr));
            }
        }
Пример #28
0
        public async Task <Room[]> SearchRoomAsync(SearchRoomRequest request)
        {
            var uriString  = _baseUrl + "/rooms?";
            var parameters = new Dictionary <string, string>()
            {
                { "name", request.ApplicationName },
                { "version", request.Version }
            };

            using (var content = new FormUrlEncodedContent(parameters))
            {
                uriString += await content.ReadAsStringAsync();
            }

            var uri = new Uri(uriString);

            using (var response = await _httpClient.GetAsync(uri))
            {
                var responseStream = await response.Content.ReadAsStreamAsync();

                var responseSerializer = new DataContractJsonSerializer(typeof(SearchRoomResponse));
                var apiResponse        = responseSerializer.ReadObject(responseStream) as SearchRoomResponse;
                if (apiResponse == null || !apiResponse.Success)
                {
                    throw new RoomApiException(apiResponse?.Error);
                }

                if (apiResponse.Rooms == null)
                {
                    return(new Room[0]);
                }

                foreach (var room in apiResponse.Rooms)
                {
                    room.ApplicationName = request.ApplicationName;
                    room.Version         = request.Version;
                }

                return(apiResponse.Rooms);
            }
        }
Пример #29
0
        /// <summary>
        /// 获取成交明细
        /// </summary>
        /// <param name="instrument_id">合约名称,如BTC-USD-SWAP</param>
        /// <param name="order_id">订单ID</param>
        /// <param name="from">分页游标开始</param>
        /// <param name="to">分页游标截至</param>
        /// <param name="limit">分页数据数量,默认100</param>
        /// <returns></returns>
        public async Task <List <Fill> > getFillsAsync(string instrument_id, string order_id, int?from, int?to, int?limit)
        {
            var url = $"{this.BASEURL}{this.SWAP_SEGMENT}/fills";

            using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, null)))
            {
                var queryParams = new Dictionary <string, string>();
                queryParams.Add("instrument_id", instrument_id);
                queryParams.Add("order_id", order_id);
                if (from.HasValue)
                {
                    queryParams.Add("from", from.Value.ToString());
                }
                if (to.HasValue)
                {
                    queryParams.Add("to", to.Value.ToString());
                }
                if (limit.HasValue)
                {
                    queryParams.Add("limit", limit.Value.ToString());
                }
                var encodedContent = new FormUrlEncodedContent(queryParams);
                var paramsStr      = await encodedContent.ReadAsStringAsync();

                var res = await client.GetAsync($"{url}?{paramsStr}");

                var contentStr = await res.Content.ReadAsStringAsync();

                if (contentStr[0] == '[')
                {
                    JContainer jContainer = JArray.Parse(contentStr);
                    var        result     = ToList <Fill>(contentStr);
                    return(result);
                }
                else
                {
                    var result = ToObject <ErrorResult>(contentStr);
                    throw new OKExException("Can't parse to list. json string = " + contentStr);
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Returns all parking session that are inside time interval
        /// </summary>
        public async Task <ResponseModel> GetSessionsInPeriod(int userId, DateTime since, DateTime until)
        {
            // IEnumerable<ParkingSession>
            CheckJwt();
            UriBuilder ub = new UriBuilder(rootUrl + "/api/parking/getsessionsinperiod");

            using (var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "userId", userId.ToString() },
                { "since", since.ToString() },
                { "until", until.ToString() }
            }))
            {
                ub.Query = await content.ReadAsStringAsync();
            }
            HttpResponseMessage response = await client.GetAsync(ub.Uri);

            string resultString = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ResponseModel>(resultString));
        }