System.Net.Http.HttpContent.ReadAsStringAsync()

Here are the examples of the csharp api System.Net.Http.HttpContent.ReadAsStringAsync() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1056 Examples 7

19 View Source File : HuobiSpotServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void SendOrder(Order order)
        {
            _portfolioCurrent = order.PortfolioNumber;

            JsonObject jsonContent = new JsonObject();

            var accountData = order.PortfolioNumber.Split('_');

            var source = "spot-api";

            if (accountData[0] == "margin")
            {
                source = "margin-api";
            }
            else if (accountData[0] == "super-margin")
            {
                source = "super-margin-api";
            }

            jsonContent.Add("account-id", accountData[1]);
            jsonContent.Add("symbol", order.SecurityNameCode);
            jsonContent.Add("type", order.Side == Side.Buy ? "buy-limit" : "sell-limit");
            jsonContent.Add("amount", order.Volume);
            jsonContent.Add("price", order.Price);
            jsonContent.Add("source", source);
            jsonContent.Add("client-order-id", order.NumberUser);

            string url = _privateUriBuilder.Build("POST", "/v1/order/orders/place");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            PlaceOrderResponse orderResponse = JsonConvert.DeserializeObject<PlaceOrderResponse>(result);

            if (orderResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else
            {
                SendLogMessage($"Order exchange error num {order.NumberUser} : {orderResponse.errorMessage}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }

19 View Source File : GoogleCredential.cs
License : Apache License 2.0
Project Creator : aloneguid

public async Task<string> RequestAccessTokenAsync(CancellationToken taskCancellationToken)
      {
         string replacedertion = Createreplacedertion(CreatePayload());

         var request = new HttpRequestMessage(HttpMethod.Post, TokenServerUrl);
         request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
         {
            ["replacedertion"] = replacedertion,
            ["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
         });
         HttpResponseMessage response = await _http.SendAsync(request);
         response.EnsureSuccessStatusCode();
         string json = await response.Content.ReadreplacedtringAsync();
         TokenResponse tr = JsonSerializer.Deserialize<TokenResponse>(json);

         return tr.AccessToken;
      }

19 View Source File : CheckUtil.cs
License : MIT License
Project Creator : actions

public static async Task<CheckResult> CheckHttpsGetRequests(this IHostContext hostContext, string url, string pat, string expectedHeader)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Send HTTPS Request (GET) to {url} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                using (var _ = new HttpEventSourceListener(result.Logs))
                using (var httpClientHandler = hostContext.CreateHttpClientHandler())
                using (var httpClient = new HttpClient(httpClientHandler))
                {
                    httpClient.DefaultRequestHeaders.UserAgent.AddRange(hostContext.UserAgents);
                    if (!string.IsNullOrEmpty(pat))
                    {
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", pat);
                    }

                    var response = await httpClient.GetAsync(url);

                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http status code: {response.StatusCode}");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response headers: {response.Headers}");

                    var responseContent = await response.Content.ReadreplacedtringAsync();
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response body: {responseContent}");
                    if (response.IsSuccessStatusCode)
                    {
                        if (response.Headers.Contains(expectedHeader))
                        {
                            result.Preplaced = true;
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} succeed");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        }
                        else
                        {
                            result.Preplaced = false;
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} succeed but doesn't have expected HTTP response Header '{expectedHeader}'.");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        }
                    }
                    else
                    {
                        result.Preplaced = false;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} failed with {response.StatusCode}");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Https request 'GET' to {url} failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 View Source File : HuobiFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void GetPortfolios()
        {
            if (Portfolios == null)
            {
                return;
            }
            foreach (var portfolio in Portfolios)
            {
                string url = _privateUriBuilder.Build("POST", "/api/v1/contract_account_info");

                StringContent httpContent = new StringContent(new JsonObject().ToString(), Encoding.UTF8, "application/json");

                var httpClient = new HttpClient();

                var response = httpClient.PostAsync(url, httpContent).Result;

                string result = response.Content.ReadreplacedtringAsync().Result;

                if (result.Contains("Incorrect Access key"))
                {
                    SendLogMessage("Huobi: Incorrect Access API key",LogMessageType.Error);
                    return;
                }

                FuturesAccountInfo accountInfo = JsonConvert.DeserializeObject<FuturesAccountInfo>(result);

                portfolio.ClearPositionOnBoard();

                for (int i = 0; accountInfo.data != null && i < accountInfo.data.Count; i++)
                {
                    var currentData = accountInfo.data[i];

                    PositionOnBoard pos = new PositionOnBoard();
                    pos.SecurityNameCode = currentData.symbol;
                    pos.ValueBegin = currentData.margin_available;
                    pos.ValueCurrent = currentData.margin_available;
                    pos.ValueBlocked = currentData.margin_frozen;

                    portfolio.SetNewPosition(pos);
                }
            }

            OnPortfolioEvent(Portfolios);
        }

19 View Source File : PortalTrackingTrace.cs
License : MIT License
Project Creator : Adoxio

private async Task AuthDCICall(JObject interactionJson, string hubUri, string policyName, string sig, string portalId)
		{
			try
			{
				if (string.IsNullOrEmpty(hubUri) || string.IsNullOrEmpty(sig) || string.IsNullOrEmpty(policyName) || HttpClient == null)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Exception,
						$"LogJourneyEvent: The DCI App Settings are not set in webapp {PortalId}");

					return;
				}

				var token = ComputeTokenSignature(hubUri, sig, policyName);

				var request = new HttpRequestMessage()
				{
					RequestUri = new Uri(hubUri + PutInteractionsUriSuffix),
					Method = HttpMethod.Post,
					Content = new StringContent(interactionJson.ToString(), Encoding.UTF8, "application/json")
				};
				request.Headers.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", token);
				request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

				ADXTrace.Instance.TraceInfo(TraceCategory.Application,
					$"LogJourneyEvent: Pre-DCI Post PortalId: {portalId}");

				var result = await HttpClient.SendAsync(request);

				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.DCI, HttpContextBase, "dci", 1, null, "create");

				ADXTrace.Instance.TraceInfo(TraceCategory.Application,
					$"LogJourneyEvent: Post-DCI Post PortalId: {portalId} {result.StatusCode}");

				if (!result.IsSuccessStatusCode)
				{
					var response = await result.Content.ReadreplacedtringAsync();

					ADXTrace.Instance.TraceError(TraceCategory.Exception,
						$"LogJourneyEvent: The DCI post was not successful. Http Code: {result.StatusCode} HttpContent: {response} PortalId: {portalId}");

					request.Dispose();

					result.Dispose();
				}
				else
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application,
						$"LogJourneyEvent: The DCI post was successful. Http Code: {result.StatusCode} PortalId: {portalId}");

					request.Dispose();

					result.Dispose();
				}

			}
			catch (Exception ex)
			{
				var message = string.Empty;
				while (ex != null)
				{
					message = message + " \n" + ex.Message;
					ex = ex.InnerException;
				}
				ADXTrace.Instance.TraceError(TraceCategory.Exception,
					$"LogJourneyEvent: DCI received unexpected exception. Message: {message} CrmInteractionId: {interactionJson[Diagnostics.Constants.PortalTrackingCrmInteractionId]} PortalId: {portalId}");
			}
			
		}

19 View Source File : BitfinexApi.cs
License : MIT License
Project Creator : aabiryukov

private string GetRestResponse(BitfinexPostBase obj)
		{
			HttpRequestMessage request;
			{
				var jsonObj = JsonConvert.SerializeObject(obj);
				var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonObj));
				request = new HttpRequestMessage(HttpMethod.Post, obj.Request);
				request.Headers.Add(ApiBfxKey, ApiKey);
				request.Headers.Add(ApiBfxPayload, payload);
				request.Headers.Add(ApiBfxSig, GetHexHashSignature(payload));
			}

			var responseMessage = WebApi.Client.SendAsync(request).Result;
			var response = responseMessage.Content.ReadreplacedtringAsync().Result;

			CheckResultCode(responseMessage.StatusCode, response);

			return response;
		}

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

public async Task<byte[]> ReadAsync(IOPath path, long offset, long count)
      {
         HttpResponseMessage response = await SendAsync(CreateReadRequest(path, offset, count));
         response.EnsureSuccessStatusCode();
         ReadResponse rr = JsonSerializer.Deserialize<ReadResponse>(await response.Content.ReadreplacedtringAsync());
         return Convert.FromBase64String(rr.Base64EncodedData);
      }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());

                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

private async Task<Tuple<IReadOnlyCollection<SqlQueryBase>, long>> ListSqlQueries(long pageNo, long pageSize)
      {
         // https://redocly.github.io/redoc/?url=https://docs.microsoft.com/azure/databricks/_static/api-refs/queries-dashboards-2.0-azure.yaml#operation/sql-replacedytics-get-queries

         // pages are 1 - based, not 0 like normal people!
         var request = new HttpRequestMessage(HttpMethod.Get, $"{_sqlBase}/queries?page={pageNo + 1}&page_size={pageSize}");
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         ListSqlQueriesResponse r = JsonSerializer.Deserialize<ListSqlQueriesResponse>(rjson);

         return new Tuple<IReadOnlyCollection<SqlQueryBase>, long>(r.Results, r.Count);
      }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : FtxRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private async Task<string> CallAsync(HttpMethod method, string endpoint, string body = null)
        {
            var request = new HttpRequestMessage(method, endpoint);

            if (body != null)
            {
                request.Content = new StringContent(body, Encoding.UTF8, "application/json");
            }

            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            var result = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            return result;
        }

19 View Source File : SourceBase.cs
License : MIT License
Project Creator : aivarasatk

protected async Task<string> UrlGetResponseString(string url)
        {
            var response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadreplacedtringAsync();
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

private string InternalQuery(NameValueDictionary args)
	    {
		    lock (m_nonceLock)
		    {
			    args.Add("nonce", GetNonce().ToString(CultureInfo.InvariantCulture));

			    var dataStr = BuildPostData(args);
			    var data = Encoding.ASCII.GetBytes(dataStr);

                using (var httpContent = new FormUrlEncodedContent(args))
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Post, WebApi.RootUrl + "/tapi"))
                    {
                        request.Headers.Add("Key", m_key);
                        request.Headers.Add("Sign", ByteArrayToString(m_hashMaker.ComputeHash(data)).ToLowerInvariant());
                        request.Content = httpContent;

                        var response = WebApi.Client.SendAsync(request).Result;
                        var resultString = response.Content.ReadreplacedtringAsync().Result;
                        return resultString;
                    }
                }
		    }
	    }

19 View Source File : HuobiFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void CancelOrder(Order order)
        {
            JsonObject jsonContent = new JsonObject();

            var contractData = order.SecurityNameCode.Split('_');

            jsonContent.Add("order_id", order.NumberMarket);
            jsonContent.Add("client_order_id", order.NumberUser);
            jsonContent.Add("symbol", contractData[0]);

            string url = _privateUriBuilder.Build("POST", "/api/v1/contract_cancel");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            CancelFuturesOrderResponse cancelResponse = JsonConvert.DeserializeObject<CancelFuturesOrderResponse>(result);

            if (cancelResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} canceled.", LogMessageType.Trade);
                order.State = OrderStateType.Cancel;
                OnOrderEvent(order);
            }
            else
            {
                SendLogMessage($"Error on order cancel num {order.NumberUser} : {cancelResponse.data.errors}", LogMessageType.Error);
            }
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPatchWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PatchAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    //Console.WriteLine($"Content: {content}");
                    result = content;
                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

private async Task Ls(IOPath path, List<IOEntry> container, bool recurse)
      {
         var request = new HttpRequestMessage(HttpMethod.Get, $"{_dbfsBase}/list");
         request.Content = new StringContent(JsonSerializer.Serialize(new ListRequest { Path = path ?? IOPath.Root }));
         HttpResponseMessage response = await SendAsync(request);
         if(response.StatusCode == HttpStatusCode.NotFound)
            return;
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         ListResponse lr = JsonSerializer.Deserialize<ListResponse>(rjson);

         if((lr?.Files?.Length ?? 0) == 0)
            return;

         var batch = lr.Files.Select(fi => new IOEntry(fi.IsDir ? fi.Path + "/" : fi.Path) { Size = fi.IsDir ? null : fi.FileSize }).ToList();
         container.AddRange(batch);

         if(recurse)
         {
            foreach(IOEntry folder in batch.Where(e => e.Path.IsFolder))
            {
               await Ls(folder.Path, container, recurse);
            }
         }
      }

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod2(string method, NameValueCollection jParams)
		{
			var args = new NameValueDictionary();

			args.Add("api_key", m_accessKey);

			if (jParams != null)
			{
				foreach (var key in jParams.AllKeys)
				{
					args.Add(key, jParams[key]);
				}
			}

			var sign = GetSignature(args, m_secretKey);
			args.Add("sign", sign);

			var httpContent = new FormUrlEncodedContent(args);
			var response = WebApi.Client.PostAsync(method + ".do", httpContent).Result;
			var resultString = response.Content.ReadreplacedtringAsync().Result;
			return resultString;
		}

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

public async Task<IReadOnlyCollection<ClusterInfo>> ListAllClusters()
      {
         var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiBase20}/clusters/list");
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         ClustersListReponse lst = JsonSerializer.Deserialize<ClustersListReponse>(rjson);

         return (lst == null || lst.Clusters == null || lst.Clusters.Length == 0)
            ? new ClusterInfo[0]
            : lst.Clusters.ToArray();

      }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallDeleteWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.DeleteAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;

                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

public async Task<IReadOnlyCollection<ObjectInfo>> WorkspaceLs(IOPath path)
      {
         var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiBase20}/workspace/list");
         request.Content = new StringContent(JsonSerializer.Serialize(new WorkspaceLsRequest { Path = path }));
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         WorkspaceLsResponse objs = JsonSerializer.Deserialize<WorkspaceLsResponse>(rjson);
         return objs.Objects;
      }

19 View Source File : VssOAuthTokenHttpClient.cs
License : MIT License
Project Creator : actions

public async Task<VssOAuthTokenResponse> GetTokenAsync(
            VssOAuthGrant grant,
            VssOAuthClientCredential credential,
            VssOAuthTokenParameters tokenParameters = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            VssTraceActivity traceActivity = VssTraceActivity.Current;
            using (HttpClient client = new HttpClient(CreateMessageHandler(this.AuthorizationUrl)))
            {
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, this.AuthorizationUrl);
                requestMessage.Content = CreateRequestContent(grant, credential, tokenParameters);
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (VssClientHttpRequestSettings.Default.UseHttp11)
                {
                    requestMessage.Version = HttpVersion.Version11;
                }

                foreach (var headerVal in VssClientHttpRequestSettings.Default.UserAgent)
                {
                    if (!requestMessage.Headers.UserAgent.Contains(headerVal))
                    {
                        requestMessage.Headers.UserAgent.Add(headerVal);
                    }
                }

                using (var response = await client.SendAsync(requestMessage, cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    string correlationId = "Unknown";
                    if (response.Headers.TryGetValues("x-ms-request-id", out IEnumerable<string> requestIds))
                    {
                        correlationId = string.Join(",", requestIds);
                    }
                    VssHttpEventSource.Log.AADCorrelationID(correlationId);

                    if (IsValidTokenResponse(response))
                    {
                        return await response.Content.ReadAsAsync<VssOAuthTokenResponse>(new[] { m_formatter }, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        var responseContent = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);
                        throw new VssServiceResponseException(response.StatusCode, responseContent, null);
                    }
                }
            }
        }

19 View Source File : EdgeUpdate.cs
License : MIT License
Project Creator : ADeltaX

private async Task<IResult<string>> SendRequest(string path, HttpMethod reqMethod, string content = "")
        {
            var req = CreateRequestHeader(reqMethod, $"https://{URL}/{path}");

            if (reqMethod == HttpMethod.Post)
                req.Content = new StringContent(content, Encoding.UTF8, "application/json");

            try
            {
                var response = await _hc.SendAsync(req);

                if (response.IsSuccessStatusCode)
                    return new Result<string>(true, await response.Content.ReadreplacedtringAsync());
                else
                    return new Result<string>(false, "BOH", ResultType.Other); //TODO: replace BOH with something more useful

            }
            catch (Exception ex)
            {
                return new Result<string>(false, ex.Message, ResultType.Exception);
            }
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    //Console.WriteLine($"Content: {content}");
                    result = content;

                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static async void CheckForUpdate(bool userTriggered)
		{
			HttpResponseMessage response;

			try
			{
				// Get the latest release info from GitHub API
				HttpClient httpClient = new HttpClient();
				httpClient.DefaultRequestHeaders.Add("User-Agent", "AHeroicLlama/Mappalachia");
				response = await httpClient.GetAsync("https://api.github.com/repos/AHeroicLlama/Mappalachia/releases/latest");

				if (!response.IsSuccessStatusCode)
				{
					if (userTriggered)
					{
						CheckForUpdatesManual("HTTP request error: " + response.StatusCode);
					}

					return;
				}
			}
			catch (Exception)
			{
				if (userTriggered)
				{
					CheckForUpdatesManual("Networking error attempting to check for updates.");
				}

				return;
			}

			try
			{
				// Extract the value of 'tag_name' from the json string
				string responseContent = await response.Content.ReadreplacedtringAsync();
				string tagName = "\"tag_name\":";
				int tagValueStart = responseContent.IndexOf(tagName) + tagName.Length;
				int tagValueLength = responseContent.Substring(tagValueStart).IndexOf(",");
				string latestVersion = responseContent.Substring(tagValueStart, tagValueLength).Replace("\"", string.Empty);

				// Verify the version string is in the format "x.y.y.y" where x is 1-999 and y is 0-999
				Regex verifyVersion = new Regex(@"^[1-9]{1,3}(\.[0-9]{1,3}){3}$");

				// We got a valid version string from GitHub
				if (verifyVersion.IsMatch(latestVersion))
				{
					if (currentVersion != latestVersion)
					{
						PromptForUpdate(latestVersion);
					}
					else if (userTriggered)
					{
						Notify.Info("Mappalachia is up to date.\n" +
							"(Version " + currentVersion + ")");
					}
				}
				else
				{
					throw new ArgumentException("Version number parsed from response was of an incorrect format.");
				}
			}
			catch (Exception)
			{
				if (userTriggered)
				{
					CheckForUpdatesManual("Unable to correctly identify latest release from API response.");
				}

				return;
			}
		}

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());

                    //Console.WriteLine($"Content: {content}");
                    result = content;

                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : HuobiSpotServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void CancelOrder(Order order)
        {
            string url = _privateUriBuilder.Build("POST", "/v1/order/orders/submitCancelClientOrder");

            string body = $"{{ \"client-order-id\":\"{order.NumberUser}\" }}";

            StringContent httpContent = new StringContent(body, Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            CancelOrderByClientResponse cancelResponse = JsonConvert.DeserializeObject<CancelOrderByClientResponse>(result);

            if (cancelResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} canceled.", LogMessageType.Trade);
                order.State = OrderStateType.Cancel;
                OnOrderEvent(order);
            }
            else
            {
                SendLogMessage($"Error on order cancel num {order.NumberUser} : {cancelResponse.errorMessage}", LogMessageType.Error);
            }
        }

19 View Source File : WebHook.cs
License : MIT License
Project Creator : akaskela

protected override void Execute(CodeActivityContext context)
        {
            string body = string.Empty;
            var workflowContext = context.GetExtension<IWorkflowContext>();

            if(!string.IsNullOrEmpty(RequestBody.Get<string>(context)))
            {
                body = RequestBody.Get<string>(context);
            }

            List<string> headers = new List<string>();

            var requestHeaders = RequestHeaders.Get<string>(context)?.Split(';');
            if (requestHeaders != null)
            {
                headers.AddRange(requestHeaders);
            }

            using (var client = new HttpClient())
            {
                foreach(var header in headers)
                {
                    var headerKeyValue = header.Split(':');

                    client.DefaultRequestHeaders.Add(headerKeyValue[0], headerKeyValue[1]);
                }

                var content = new StringContent(body, Encoding.UTF8, "application/json");

                System.Threading.Tasks.Task<HttpResponseMessage> response = null;
                if (this.RequestMethod != null)
                {
                    OptionSetValue value = this.RequestMethod.Get<OptionSetValue>(context);
                    if (value != null && value.Value != 0)
                    {
                        response = SendRequest(context, client, value.Value, content);
                    }
                }
                if (response != null)
                {
                    response.Result.EnsureSuccessStatusCode();
                    StringBuilder delimitedHeaders = new StringBuilder();
                    foreach (var header in response.Result.Headers)
                    {
                        if (delimitedHeaders.Length > 0)
                        {
                            delimitedHeaders.Append(";");
                        }
                        delimitedHeaders.Append($"{header.Key}:{header.Value}");
                    }
                    ResponseHeaders.Set(context, delimitedHeaders.ToString());
                    var responseString = response.Result.Content.ReadreplacedtringAsync();
                    ResponseBody.Set(context, responseString.Result);
                }
            }
        }

19 View Source File : TrainDataService.cs
License : MIT License
Project Creator : 42skillz

public async Task<string> GetTrain(string train)
        {
            string jsonTrainTopology;
            using (var client = new HttpClient())
            {
                var value = new MediaTypeWithQualityHeaderValue("application/json");
                client.BaseAddress = new Uri(_uriTrainDataService);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(value);
                // HTTP GET
                var response = await client.GetAsync($"api/data_for_train/{train}");
                response.EnsureSuccessStatusCode();
                jsonTrainTopology = await response.Content.ReadreplacedtringAsync();
            }
            return jsonTrainTopology;
        }

19 View Source File : FtxRestApi.cs
License : Apache License 2.0
Project Creator : AlexWan

private async Task<string> CallAsyncSign(HttpMethod method, string endpoint, string sign, string body = null)
        {
            var request = new HttpRequestMessage(method, endpoint);

            if (body != null)
            {
                request.Content = new StringContent(body, Encoding.UTF8, "application/json");
            }

            request.Headers.Add("FTX-KEY", _client.ApiKey);
            request.Headers.Add("FTX-SIGN", sign);
            request.Headers.Add("FTX-TS", _nonce.ToString());

            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            var result = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            return result;
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());

                    //Console.WriteLine($"Content: {content}");
                    result = content;
                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : HuobiFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void SendOrder(Order order)
        {
            _portfolioCurrent = order.PortfolioNumber;

            JsonObject jsonContent = new JsonObject();

            var contractData = order.SecurityNameCode.Split('_');

            var contractType = "quarter";

            if (contractData[1] == "CW")
            {
                contractType = "this_week";
            }
            else if (contractData[1] == "NW")
            {
                contractType = "next_week";
            }

            jsonContent.Add("symbol", contractData[0]);
            jsonContent.Add("contract_type", contractType);
            jsonContent.Add("client_order_id", order.NumberUser);
            jsonContent.Add("price", order.Price);
            jsonContent.Add("volume", order.Volume);
            jsonContent.Add("direction", order.Side == Side.Buy ? "buy" : "sell");

            // если ордер открывающий позицию - тут "open", если закрывающий - "close"
            if (order.PositionConditionType == OrderPositionConditionType.Close)
            {
                jsonContent.Add("offset", "close");
            }
            else
            {
                jsonContent.Add("offset", "open");
            }

            jsonContent.Add("lever_rate", "10");
            jsonContent.Add("order_price_type", "limit");

            string url = _privateUriBuilder.Build("POST", "/api/v1/contract_order");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            PlaceFuturesOrderResponse orderResponse = JsonConvert.DeserializeObject<PlaceFuturesOrderResponse>(result);

            if (orderResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else
            {
                //err_msg
                dynamic errorData = JToken.Parse(result);
                string errorMsg = errorData.err_msg;

                SendLogMessage($"Order exchange error num {order.NumberUser} : {errorMsg}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }

19 View Source File : BitstampApi.cs
License : MIT License
Project Creator : aabiryukov

private string Query(string operation, NameValueDictionary args = null)
        {
			if(args == null)
				args = new NameValueDictionary();

			lock (m_nonceLock)
			{
				var nonce = GetNonce();
				var signature = GetSignature(nonce);

				args.Add("key", m_key);
				args.Add("signature", signature);
				args.Add("nonce", nonce.ToString(CultureInfo.InvariantCulture));

				var path = new Uri("https://www.bitstamp.net/api/" + operation + "/");

				var httpContent = new FormUrlEncodedContent(args);
				var response = WebApi.Client.PostAsync(path, httpContent).Result;
				var resultString = response.Content.ReadreplacedtringAsync().Result;
				return resultString;
			}
        }

19 View Source File : HuobiFuturesSwapServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void GetPortfolios()
        {
            if (Portfolios == null)
            {
                return;
            }
            foreach (var portfolio in Portfolios)
            {
                string url = _privateUriBuilder.Build("POST", "/swap-api/v1/swap_account_info");

                StringContent httpContent = new StringContent(new JsonObject().ToString(), Encoding.UTF8, "application/json");

                var httpClient = new HttpClient();

                var response = httpClient.PostAsync(url, httpContent).Result;

                string result = response.Content.ReadreplacedtringAsync().Result;

                if (result.Contains("Incorrect Access key"))
                {
                    SendLogMessage("Huobi: Incorrect Access API key", LogMessageType.Error);
                    return;
                }

                FuturesAccountInfo accountInfo = JsonConvert.DeserializeObject<FuturesAccountInfo>(result);

                portfolio.ClearPositionOnBoard();

                for (int i = 0; accountInfo.data != null && i < accountInfo.data.Count; i++)
                {
                    var currentData = accountInfo.data[i];

                    PositionOnBoard pos = new PositionOnBoard();
                    pos.SecurityNameCode = currentData.symbol;
                    pos.ValueBegin = currentData.margin_available;
                    pos.ValueCurrent = currentData.margin_available;
                    pos.ValueBlocked = currentData.margin_frozen;

                    portfolio.SetNewPosition(pos);
                }
            }

            OnPortfolioEvent(Portfolios);
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPatchWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PatchAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : HuobiFuturesSwapServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void CancelOrder(Order order)
        {
            JsonObject jsonContent = new JsonObject();

            jsonContent.Add("order_id", order.NumberMarket);
            jsonContent.Add("client_order_id", order.NumberUser);
            jsonContent.Add("contract_code", order.SecurityNameCode);

            string url = _privateUriBuilder.Build("POST", "/swap-api/v1/swap_cancel");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            CancelFuturesOrderResponse cancelResponse = JsonConvert.DeserializeObject<CancelFuturesOrderResponse>(result);

            if (cancelResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} canceled.", LogMessageType.Trade);
                order.State = OrderStateType.Cancel;
                OnOrderEvent(order);
            }
            else
            {
                SendLogMessage($"Error on order cancel num {order.NumberUser} : {cancelResponse.data.errors}", LogMessageType.Error);
            }
        }

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod2(string method, NameValueCollection jParams)
		{
            // add some more args for authentication
            var seconds = UnixTime.GetFromDateTime(DateTime.UtcNow);

            var args = new NameValueDictionary
		    {
                {"created", seconds.ToString(CultureInfo.InvariantCulture)},
                {"access_key", m_accessKey},
                {"method", method},
                {"secret_key", m_secretKey}
            };

		    if (jParams != null)
			{
				foreach (var key in jParams.AllKeys)
				{
					args.Add(key, jParams[key]);
				}
			}

            var argsSortedByKey = args.OrderBy(kvp => kvp.Key).ToList();

            var sign = GetSignature(argsSortedByKey);
            argsSortedByKey.Add( new KeyValuePair<string, string>("sign", sign));

			var httpContent = new FormUrlEncodedContent(argsSortedByKey);
			var response = WebApi.Client.PostAsync("apiv3/" + method, httpContent).Result;
			var resultString = response.Content.ReadreplacedtringAsync().Result;

            if (resultString.Contains("code"))
            {
                var error = JsonConvert.DeserializeObject<HuobiError>(resultString);
                throw new HuobiException(method, "Request failed with code: " + error.Code);
            }

            return resultString;
		}

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

public byte[] Read(IOPath path, long offset, long count)
      {
         HttpResponseMessage response = Send(CreateReadRequest(path, offset, count));
         response.EnsureSuccessStatusCode();
         ReadResponse rr = JsonSerializer.Deserialize<ReadResponse>(response.Content.ReadreplacedtringAsync().Result);
         return Convert.FromBase64String(rr.Base64EncodedData);
      }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallDeleteWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.DeleteAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    //Console.WriteLine($"Content: {content}");
                    result = content;

                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : GoogleCloudStorage.cs
License : Apache License 2.0
Project Creator : aloneguid

public override async Task<IReadOnlyCollection<IOEntry>> Ls(IOPath path, bool recurse = false, CancellationToken cancellationToken = default)
      {
         if(path != null && !path.IsFolder)
            throw new ArgumentException("path needs to be a folder", nameof(path));

         // https://cloud.google.com/storage/docs/json_api/v1/objects/list

         string prefix = IOPath.IsRoot(path) ? null : IOPath.Normalize(path, true, true);
         string delimiter = recurse ? null : "/";
         string url = "";
         //string url = "/storage/v1/b/{bucketName}/o";
         if(null != prefix)
            url += "&prefix=" + prefix.UrlEncode();
         if(null != delimiter)
            url += "&delimiter=" + delimiter.UrlEncode();
         if(url.Length > 1)
            url = "/?" + url.Substring(1);
         url = $"/storage/v1/b/{_bucketName}/o" + url;
         var request = new HttpRequestMessage(HttpMethod.Get, url);
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         ListResponse lr = JsonSerializer.Deserialize<ListResponse>(rjson);

         var result =  ConvertBatch(lr).ToList();

         if(recurse)
         {
            Implicits.replacedumeImplicitFolders(path, result);
         }

         return result;
      }

19 View Source File : UserManager.cs
License : Apache License 2.0
Project Creator : ac87

private async Task GetGooglePlusUserData(string accessToken)
        {
            try
            {
                HttpClient client = new HttpClient();
                var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;

                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {                  
                    string outputData = await output.Content.ReadreplacedtringAsync();
                    GoogleUserData newUserData = JsonConvert.DeserializeObject<GoogleUserData>(outputData);

                    if (newUserData != null)
                    {                                                
                        string file = Utils.GetDataStoreFolder() + newUserData.id;
                        string jsonFile = file + ".json";
                        string imageFile = file + ".png";

                        if (File.Exists(jsonFile))
                        {
                            string json = File.ReadAllText(jsonFile);
                            GoogleUserData existingUserData = JsonConvert.DeserializeObject<GoogleUserData>(json);
                            if (newUserData.picture != null &&
                                (!File.Exists(imageFile) ||
                                 existingUserData.picture != null && existingUserData.picture != newUserData.picture))
                                Utils.GetImage(newUserData.picture, imageFile);
                        }
                        else
                            Utils.GetImage(newUserData.picture, imageFile);

                        // overwrites existing file
                        File.WriteAllText(jsonFile, outputData);

                        _userData = newUserData;
                    }
                }
            }
            catch (Exception)
            {
                // return some rubbish for now.
                _userData = new GoogleUserData() { id = "1234567890", name = "Unknown" };
            }
        }

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

private async Task EnsureSuccessOrThrow(HttpResponseMessage response)
      {
         if(response.IsSuccessStatusCode)
            return;

         // read response body
         string body = await response.Content.ReadreplacedtringAsync();
         ErrorResponse jem = JsonSerializer.Deserialize<ErrorResponse>(body);

         throw new HttpRequestException(
            $"request failed with code {(int)response.StatusCode} '{response.StatusCode}'. {jem.Message}.");
      }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;

                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());

                    //Console.WriteLine($"Content: {content}");
                    result = content;
                    
                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : DatabricksRestClient.cs
License : Apache License 2.0
Project Creator : aloneguid

public async Task<IReadOnlyCollection<ClusterEvent>> ListClusterEvents(string clusterId)
      {
         var request = new HttpRequestMessage(HttpMethod.Post, $"{_apiBase20}/clusters/events");
         request.Content = new StringContent($"{{\"cluster_id\":\"{clusterId}\"}}");
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();

         EventsListReponse evts = JsonSerializer.Deserialize<EventsListReponse>(rjson);

         return evts.Events;
      }

19 View Source File : ConfigurationManager.cs
License : MIT License
Project Creator : actions

private async Task<GitHubRunnerRegisterToken> GetJITRunnerTokenAsync(string githubUrl, string githubToken, string tokenType)
        {
            var githubApiUrl = "";
            var gitHubUrlBuilder = new UriBuilder(githubUrl);
            var path = gitHubUrlBuilder.Path.Split('/', '\\', StringSplitOptions.RemoveEmptyEntries);
            if (path.Length == 1)
            {
                // org runner
                if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/orgs/{path[0]}/actions/runners/{tokenType}-token";
                }
                else
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/orgs/{path[0]}/actions/runners/{tokenType}-token";
                }
            }
            else if (path.Length == 2)
            {
                // repo or enterprise runner.
                var repoScope = "repos/";
                if (string.Equals(path[0], "enterprises", StringComparison.OrdinalIgnoreCase))
                {
                    repoScope = "";
                }

                if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
                }
                else
                {
                    githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
                }
            }
            else
            {
                throw new ArgumentException($"'{githubUrl}' should point to an org or repository.");
            }

            using (var httpClientHandler = HostContext.CreateHttpClientHandler())
            using (var httpClient = new HttpClient(httpClientHandler))
            {
                var base64EncodingToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"github:{githubToken}"));
                HostContext.SecretMasker.AddValue(base64EncodingToken);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", base64EncodingToken);
                httpClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
                httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");

                var response = await httpClient.PostAsync(githubApiUrl, new StringContent(string.Empty));

                if (response.IsSuccessStatusCode)
                {
                    Trace.Info($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
                    var jsonResponse = await response.Content.ReadreplacedtringAsync();
                    return StringUtil.ConvertFromJson<GitHubRunnerRegisterToken>(jsonResponse);
                }
                else
                {
                    _term.WriteError($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
                    var errorResponse = await response.Content.ReadreplacedtringAsync();
                    _term.WriteError(errorResponse);
                    response.EnsureSuccessStatusCode();
                    return null;
                }
            }
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<string> CallGetHTMLWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            string result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadreplacedtringAsync();
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    result = await response.Content.ReadreplacedtringAsync();
                    Console.WriteLine($"Content: {result}");
                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;

                }
                Console.ResetColor();
            }
            return result;
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    //Console.WriteLine($"Content: {content}");
                    result = content;
                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public async Task<string> CallGetHTMLWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            string result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadreplacedtringAsync();
                    //Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    //Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    result = await response.Content.ReadreplacedtringAsync();
                    //Console.WriteLine($"Content: {result}");

                }
                //Console.ResetColor();
            }
            return result;
        }

19 View Source File : BookingReferenceService.cs
License : MIT License
Project Creator : 42skillz

private async Task<string> GetBookRef(HttpClient client)
        {
            var value = new MediaTypeWithQualityHeaderValue("application/json");
            client.BaseAddress = new Uri(_uriBookingReferenceService);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(value);

            // HTTP GET
            var response = await client.GetAsync("/booking_reference");
            response.EnsureSuccessStatusCode();

            var bookingRef = await response.Content.ReadreplacedtringAsync();
            return bookingRef;
        }

19 View Source File : HuobiFuturesSwapServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void SendOrder(Order order)
        {
            _portfolioCurrent = order.PortfolioNumber;

            JsonObject jsonContent = new JsonObject();

            jsonContent.Add("contract_code", order.SecurityNameCode);
            jsonContent.Add("client_order_id", order.NumberUser);
            jsonContent.Add("price", order.Price);
            jsonContent.Add("volume", order.Volume);
            jsonContent.Add("direction", order.Side == Side.Buy ? "buy" : "sell");

            // если ордер открывающий позицию - тут "open", если закрывающий - "close"
            if (order.PositionConditionType == OrderPositionConditionType.Close)
            {
                jsonContent.Add("offset", "close");
            }
            else
            {
                jsonContent.Add("offset", "open");
            }

            jsonContent.Add("lever_rate", "10");
            jsonContent.Add("order_price_type", "limit");

            string url = _privateUriBuilder.Build("POST", "/swap-api/v1/swap_order");

            StringContent httpContent = new StringContent(jsonContent.ToString(), Encoding.UTF8, "application/json");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync(url, httpContent).Result;

            string result = response.Content.ReadreplacedtringAsync().Result;

            PlaceFuturesOrderResponse orderResponse = JsonConvert.DeserializeObject<PlaceFuturesOrderResponse>(result);

            if (orderResponse.status == "ok")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else
            {
                //err_msg
                dynamic errorData = JToken.Parse(result);
                string errorMsg = errorData.err_msg;

                SendLogMessage($"Order exchange error num {order.NumberUser} : {errorMsg}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }

See More Examples