コード例 #1
0
        public async Task <string> getSharePointAccessToken(string siteUrl)
        {
            HttpClient client = new HttpClient();

            KeyValuePair <string, string>[] body = new KeyValuePair <string, string>[]
            {
                new KeyValuePair <string, string>("grant_type", "client_credentials"),
                new KeyValuePair <string, string>("client_id", $"{clientID}@{tenantID}"),
                new KeyValuePair <string, string>("resource", $"{spPrinciple}/{siteUrl}@{tenantID}".Replace("https://", "")),
                new KeyValuePair <string, string>("client_secret", clientSecret)
            };
            var    content       = new FormUrlEncodedContent(body);
            var    contentLength = content.ToString().Length;
            string token         = "";

            using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
            {
                if (response.Content != null)
                {
                    string responseString = await response.Content.ReadAsStringAsync();

                    JObject data = JObject.Parse(responseString);
                    token = data.Value <string>("access_token");
                }
            }
            return(token);
        }
コード例 #2
0
        static async void NetworkRegister(string NewNodeUrl)
        {
            // automatically notify node you are registering about this node
            using (var client = new HttpClient())
            {
                try
                {
                    Console.WriteLine($"  Initiating API call: calling {NewNodeUrl} node-register {baseAddress}");

                    var content = new FormUrlEncodedContent(
                        new Dictionary <string, string>
                    {
                        { "", baseAddress }
                    }
                        );

                    Console.Error.WriteLine(content.ToString());

                    var response = await client.PostAsync(NewNodeUrl + "api/network/register", content);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("  " + ex.Message);
                    Console.ResetColor();
                }
            }
        }
コード例 #3
0
        async public void GetMapObjects(GoogleMap gMap, string region, DateTime?timestamp)
        {
            string queryString;

            if (timestamp != null)
            {
                var query = new FormUrlEncodedContent(new Dictionary <string, string>()
                {
                    { "region", region },
                    { "timestamp", DateTime.UtcNow.ToString() },
                }).ReadAsStringAsync().Result;
                queryString = query.ToString();
            }
            else
            {
                var query = new FormUrlEncodedContent(new Dictionary <string, string>()
                {
                    { "region", region }
                }).ReadAsStringAsync().Result;
                queryString = query.ToString();
            }
            HttpResponseMessage httpResponse = await httpClient.GetAsync(url + "byRegion?" + queryString);

            mapObjects = await httpResponse.Content.ReadAsJsonAsync <List <MapObjects> >();

            AddObjectsToMap(gMap);
        }
コード例 #4
0
        public T Post <T>(string endpoint, Dictionary <string, string> parameters) where T : _BaseDividoResponse, new()
        {
            var serializer = new DataContractJsonSerializer(typeof(T));

            var url = CreateUrl(endpoint);

            parameters = AddMerchant(parameters);
            parameters = Calculators.PostDataCalculator.FinalizeKeys(parameters);
#if FEATURE_TYPE_INFO
            var content    = new FormUrlEncodedContent(parameters);
            var streamTask = HttpClient.PostAsync(url, content).Result.Content.ReadAsStreamAsync().Result;
#else
            var nvc = new System.Collections.Specialized.NameValueCollection();
            foreach (var kvp in parameters)
            {
                nvc.Add(kvp.Key, kvp.Value);
            }
            var byteArray = WebClient.UploadValues(url, nvc);
            System.IO.Stream streamTask = new System.IO.MemoryStream(byteArray);
#endif



            var data = serializer.ReadObject(streamTask) as T;
            data.RequestUrl = url;
#if FEATURE_TYPE_INFO
            data.RequestData = content.ToString();
#endif
            ValidateResponse(data);

            return(data);
        }
コード例 #5
0
        public async Task <Token> Authorize()
        {
            var authData = string.Format("{0}:{1}", Constants.KEY, Constants.SECRET);

            Console.WriteLine("authData: {0}", authData);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));

            Console.WriteLine("authHeaderValue: {0}", authHeaderValue);

            client = new HttpClient();

            var endpoint = new Uri(Constants.HOSTNAME + Constants.AUTH_PATH);

            Console.WriteLine("endpoint: {0}", endpoint);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
            Console.WriteLine("headers: {0}", client.DefaultRequestHeaders.ToString());
            var postData = new List <KeyValuePair <string, string> >();

            postData.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));
            Console.WriteLine("postData: {0}", postData.ToString());

            HttpContent body = new FormUrlEncodedContent(postData);

            Console.WriteLine("body: {0}", body.ToString());

            HttpResponseMessage response;

            try {
                response = await client.PostAsync(endpoint, body).ConfigureAwait(false);


                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    token = JsonConvert.DeserializeObject <Token>(content);
                    Console.WriteLine("Authorize() Token: " + token.ToString());
                }
                else
                {
                    Console.WriteLine(response.ToString());
                    response.EnsureSuccessStatusCode();
                }
            }
            catch (AggregateException agex)
            {
                Console.WriteLine(@"				ERROR {0}\n{1}", agex.Message, agex.InnerException.Message);
            } catch (Exception ex) {
                Console.WriteLine(@"				ERROR {0}", ex.Message);
            }

            return(token);
        }
コード例 #6
0
        private async Task <T> PostForm <T>(string url, object request) where T : ISlackApiResponse
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            _logger.LogDebug("API POST to: {0}", url);

            var jObject = JObject.FromObject(request, _jsonSerializer);
            var values  = new Dictionary <string, string>();

            foreach (var property in jObject.Properties())
            {
                switch (property.Type)
                {
                case JTokenType.None:
                case JTokenType.Undefined:
                    break;

                case JTokenType.Boolean:
                case JTokenType.Float:
                case JTokenType.Integer:
                case JTokenType.String:
                    values.Add(property.Name, property.Value <string>());
                    break;

                case JTokenType.Object:
                    values.Add(property.Name, property.ToString());
                    break;

                default:
                    throw new SlackException($"Unsupported property type. Property: {property.Name} Type: {property.Type}");
                }
            }
            using (var content = new FormUrlEncodedContent(values))
            {
                _logger.LogDebug("API request body: {0}", content.ToString());
                return(await Post <T>(url, content));
            }
        }
コード例 #7
0
        public static async Task <JObject> PostAsync(string url, Dictionary <string, string> postDict)
        {
            if (!postDict.ContainsKey("access_token"))
            {
                postDict.Add("access_token", Https.AccessToken);
            }
            else
            {
                postDict["access_token"] = Https.AccessToken;
            }
            if (!postDict.ContainsKey("plat"))
            {
                postDict.Add("plat", Https.Plat);
            }
            else
            {
                postDict["plat"] = Https.Plat;
            }
            if (!postDict.ContainsKey("version"))
            {
                postDict.Add("version", Https.Version);
            }
            else
            {
                postDict["version"] = Https.Version;
            }
            var postData = new FormUrlEncodedContent(postDict);

            Console.WriteLine(postData.ToString());
            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip
            };

            using (var http = new HttpClient(handler))
            {
                var response = await http.PostAsync(Https.BaseApiUrl + url, postData);

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

                return((JObject)JsonConvert.DeserializeObject(data));
            }
        }
コード例 #8
0
        public static async Task <HttpResponseMessage> PostMusicUrl(string url, Dictionary <string, string> postDict)
        {
            if (!postDict.ContainsKey("access_token"))
            {
                postDict.Add("access_token", Https.AccessToken);
            }
            else
            {
                postDict["access_token"] = Https.AccessToken;
            }
            if (!postDict.ContainsKey("plat"))
            {
                postDict.Add("plat", Https.Plat);
            }
            else
            {
                postDict["plat"] = Https.Plat;
            }
            if (!postDict.ContainsKey("version"))
            {
                postDict.Add("version", Https.Version);
            }
            else
            {
                postDict["version"] = Https.Version;
            }
            var postData = new FormUrlEncodedContent(postDict);

            Console.WriteLine(postData.ToString());
            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                AllowAutoRedirect      = false
            };

            using (var http = new HttpClient(handler))
            {
                var response = await http.PostAsync(Https.BaseApiUrl + url, postData);

                return(response);
            }
        }
コード例 #9
0
        public void SaveRequest(bool RequestSave, string SaveDirectory)
        {
            string RequestFileContent = string.Empty;

            if (RequestSave)
            {
                if (mAct.GetType() == typeof(ActWebAPISoap))
                {
                    RequestFileContent = BodyString;
                    mAct.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIRest.Fields.ContentType, "XML");
                }
                else if (mAct.GetType() == typeof(ActWebAPIRest))
                {
                    if (!string.IsNullOrEmpty(BodyString))
                    {
                        RequestFileContent = BodyString;
                    }
                    else if ((mAct.RequestKeyValues.Count() > 0) && (mAct.GetInputParamValue(ActWebAPIRest.Fields.ContentType) == "XwwwFormUrlEncoded"))
                    {
                        HttpContent UrlEncoded = new FormUrlEncodedContent(ConstructURLEncoded((ActWebAPIRest)mAct));
                        RequestFileContent = UrlEncoded.ToString();
                    }
                    else if ((mAct.RequestKeyValues.Count() > 0) && (mAct.GetInputParamValue(ActWebAPIRest.Fields.ContentType) == "FormData"))
                    {
                        MultipartFormDataContent FormDataContent = new MultipartFormDataContent();
                        for (int i = 0; i < mAct.RequestKeyValues.Count(); i++)
                        {
                            FormDataContent.Add(new StringContent(mAct.RequestKeyValues[i].ValueForDriver), mAct.RequestKeyValues[i].ItemName.ToString());
                        }
                        RequestFileContent = FormDataContent.ToString();
                    }
                    else
                    {
                        RequestFileContent = RequestMessage.ToString();
                    }
                }

                string FileFullPath = Webserviceplatforminfo.SaveToFile("Request", RequestFileContent, SaveDirectory, mAct);
                mAct.AddOrUpdateReturnParamActual("Saved Request File Name", Path.GetFileName(FileFullPath));
            }
        }
コード例 #10
0
        //internal static async Task<AuthenticationResult> GetRefreshToken(IDialogContext context, string refreshToken)
        //{
        //    SharePointSettings settings = SharePointSettings.GetFromAppSettings();

        //    string spPrinciple = "00000003-0000-0ff1-ce00-000000000000";
        //    string spAuthUrl = "https://accounts.accesscontrol.windows.net/" + settings.TenantId + "/tokens/OAuth/2";

        //    KeyValuePair<string, string>[] body = new KeyValuePair<string, string>[]
        //    {
        //        new KeyValuePair<string, string>("grant_type", "refresh_token"),
        //        new KeyValuePair<string, string>("client_id", $"{settings.ClientId}@{settings.TenantId}"),
        //        new KeyValuePair<string, string>("resource", $"{spPrinciple}/{settings.TenantUrl}@{settings.TenantId}".Replace("https://", "")),
        //        new KeyValuePair<string, string>("client_secret", settings.ClientSecret),
        //        new KeyValuePair<string, string>("refresh_token", refreshToken),
        //        new KeyValuePair<string, string>("redirect_uri", settings.RedirectUrl)
        //    };

        //    var content = new FormUrlEncodedContent(body);
        //    var contentLength = content.ToString().Length;

        //    AuthenticationResult result = new AuthenticationResult();

        //    HttpClient client = new HttpClient();
        //    using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
        //    {
        //        if (response.Content != null)
        //        {
        //            string responseString = await response.Content.ReadAsStringAsync();
        //            JObject data = JObject.Parse(responseString);

        //            result.AccessToken = data.Value<string>("access_token");
        //            result.ExpiresOnUtcTicks = data.Value<long>("expires_on");
        //            result.Resource = data.Value<string>("resource");
        //            TODO: need to extend the result with more fields when available
        //        }
        //    }

        //    return result;
        //}

        public static async Task <AuthenticationResult> GetTokenByAuthCodeAsync(string code)
        {
            SharePointSettings settings = SharePointSettings.GetFromAppSettings();

            string spPrinciple = "00000003-0000-0ff1-ce00-000000000000";
            string spAuthUrl   = "https://accounts.accesscontrol.windows.net/" + settings.TenantId + "/tokens/OAuth/2";

            KeyValuePair <string, string>[] body = new KeyValuePair <string, string>[]
            {
                new KeyValuePair <string, string>("grant_type", "client_credentials"),
                new KeyValuePair <string, string>("client_id", $"{settings.ClientId}@{settings.TenantId}"),
                new KeyValuePair <string, string>("resource", $"{spPrinciple}/{settings.TenantUrl}@{settings.TenantId}".Replace("https://", "")),
                new KeyValuePair <string, string>("client_secret", settings.ClientSecret),
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("redirect_uri", settings.RedirectUrl)
            };

            var content       = new FormUrlEncodedContent(body);
            var contentLength = content.ToString().Length;

            AuthenticationResult result = new AuthenticationResult();

            HttpClient client = new HttpClient();

            using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
            {
                if (response.Content != null)
                {
                    string responseString = await response.Content.ReadAsStringAsync();

                    JObject data = JObject.Parse(responseString);

                    result.AccessToken       = data.Value <string>("access_token");
                    result.RefreshToken      = data.Value <string>("refresh_token");
                    result.ExpiresOnUtcTicks = data.Value <long>("expires_on");
                    // TODO: need to extend the result with more fields when available
                }
            }

            return(result);
        }
コード例 #11
0
        public RespuestaDto Pagar(string commerceKey, string codigoQr, string monto, string comanda, string url = "")
        {
            string urlx;

            if (url.Equals(""))
            {
                urlx = "http://api.mobile.mundopipol.com:8080/PipolRestoWeb/PipolrestoWebJson/RestoMethods/shellProducts";
            }
            else
            {
                urlx = url;
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlx));
            var            values  = new Dictionary <string, string> {
                { "commerceKey", commerceKey },
                { "tokenQR", codigoQr },
                { "amount", monto },
                { "comanda", comanda }
            };

            try
            {
                HttpClient client  = new HttpClient();
                var        content = new FormUrlEncodedContent(values);
                Console.WriteLine(content.ToString());
                var          response  = client.PostAsync(url, content).Result;
                var          respuesta = response.Content.ReadAsStringAsync().Result;
                RespuestaDto resp      = JsonConvert.DeserializeObject <RespuestaDto>(respuesta);
                return(resp);
            }
            catch (Exception ex)
            {
                throw new Exception($"Exception Plugin Pipol [{ex.Message}]");
            }
        }
コード例 #12
0
        public AwsV4.SignedResult GetSignedResult(KsyunConfig config, FormUrlEncodedContent content)
        {
            var headers = new Dictionary <string, string> {
                { "host", KsyunSmsConstants.Host }
            };
            var awsv4 = new AwsV4(config, "POST", KsyunSmsConstants.Host, headers, string.Empty, content.ToString());

            return(awsv4.Signer());
        }
コード例 #13
0
        private static async Task Dont_Follow_Redirects_And_Craft_Broken_Url_To_Get_Usage()
        {
            try
            {
                var cc = new CookieContainer();
                var h  = new HttpClientHandler()
                {
                    CookieContainer = cc,
                    //Proxy = new WebProxy("localhost", 8888), //For monitoring traffic with Fiddler
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                    AllowAutoRedirect      = false,
                };
                var c = new HttpClient(h);

                c.DefaultRequestHeaders.Add("User-Agent", "python-requests/2.18.4");
                c.DefaultRequestHeaders.Add("Accept", "*/*");
                c.DefaultRequestHeaders.Add("Connection", "keep-alive");

                Console.WriteLine("Finding req_id for login...");
                var initialResponse = await c.GetAsync("https://customer.xfinity.com/oauth/force_connect/?continue=%23%2Fdevices");

                if (initialResponse.StatusCode == HttpStatusCode.Redirect)
                {
                    initialResponse = await c.GetAsync(initialResponse.Headers.Location);

                    if (initialResponse.StatusCode == HttpStatusCode.Redirect)
                    {
                        initialResponse = await c.GetAsync(initialResponse.Headers.Location);

                        if (initialResponse.StatusCode == HttpStatusCode.Redirect)
                        {
                            initialResponse = await c.GetAsync(initialResponse.Headers.Location);
                        }
                    }
                }

                Debug.Assert(initialResponse.StatusCode == HttpStatusCode.OK);
                var body = await initialResponse.Content.ReadAsStringAsync();

                var d = new HtmlAgilityPack.HtmlDocument();
                d.LoadHtml(body);
                var dd    = d.DocumentNode.Descendants("input");
                var reqId = dd.Where(n => n.Attributes.Contains("name") && n.Attributes["name"].Value == "reqId").FirstOrDefault()?.Attributes["value"]?.Value;

                Console.WriteLine("Found req_id = {0}", reqId);

                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("user", username),
                    new KeyValuePair <string, string>("passwd", password),
                    new KeyValuePair <string, string>("reqId", reqId),
                    new KeyValuePair <string, string>("deviceAuthn", "false"),
                    new KeyValuePair <string, string>("s", "oauth"),
                    new KeyValuePair <string, string>("forceAuthn", "1"),
                    new KeyValuePair <string, string>("r", "comcast.net"),
                    new KeyValuePair <string, string>("ipAddrAuthn", "false"),
                    new KeyValuePair <string, string>("Continue", "https://oauth.xfinity.com/oauth/authorize?client_id=my-account-web&prompt=login&redirect_uri=https%3A%2F%2Fcustomer.xfinity.com%2Foauth%2Fcallback&response_type=code&state=%23%2Fdevices&response=1"),
                    new KeyValuePair <string, string>("passive", "false"),
                    new KeyValuePair <string, string>("client_id", "my-account-web"),
                    new KeyValuePair <string, string>("lang", "en"),
                });
                var payload = content.ToString();

                Console.WriteLine("Posting to login...");
                var postResult = await c.PostAsync("https://login.xfinity.com/login", content);

                if (postResult.StatusCode == HttpStatusCode.Redirect || postResult.StatusCode == HttpStatusCode.Found)
                {
                    //For reasons unknown, the server replies with an incomplete URL, but what is needed is easy enough to detect and add... though ugly.
                    if (!postResult.Headers.Location.ToString().Contains("client_id"))
                    {
                        var newQuery = "client_id=my-account-web&prompt=login&redirect_uri=https%3A%2F%2Fcustomer.xfinity.com%2Foauth%2Fcallback&response_type=code&state=%23%2Fdevices&response=1&" + postResult.Headers.Location.Query.ToString().TrimStart('?');

                        var newUri = new Uri($"https://{postResult.Headers.Location.Authority}{postResult.Headers.Location.AbsolutePath}?{newQuery}");

                        postResult = await c.GetAsync(newUri);

                        if (postResult.StatusCode == HttpStatusCode.Redirect || postResult.StatusCode == HttpStatusCode.Found)
                        {
                            postResult = await c.GetAsync(postResult.Headers.Location);

                            if (postResult.StatusCode == HttpStatusCode.Redirect || postResult.StatusCode == HttpStatusCode.Found)
                            {
                                postResult = await c.GetAsync(postResult.Headers.Location);
                            }
                        }
                    }
                }
                Debug.Assert(postResult.StatusCode == HttpStatusCode.OK);
                var postResponseContent = await postResult.Content.ReadAsStringAsync();

                Console.WriteLine("Fetching internet usage JSON");
                var getResult = await c.GetAsync("https://customer.xfinity.com/apis/services/internet/usage");

                Debug.Assert(getResult.StatusCode == HttpStatusCode.OK);
                var datausage = await getResult.Content.ReadAsStringAsync();

                Console.WriteLine("Got {0} bytes of response", datausage.Length);

                var usage = JsonConvert.DeserializeObject <DataUsage>(datausage);
                DisplayUsage(usage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during operation: {0}", ex);
            }
        }
コード例 #14
0
        private static async Task ShouldWork_But_Fails_Due_To_Bad_Redirect()
        {
            try
            {
                var cc = new CookieContainer();
                var h  = new HttpClientHandler()
                {
                    CookieContainer = cc,
                    //Proxy = new WebProxy("localhost", 8888), //For monitoring traffic with Fiddler
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                    AllowAutoRedirect      = true,
                };
                var c = new HttpClient(h);

                c.DefaultRequestHeaders.Add("User-Agent", "python-requests/2.18.4");
                c.DefaultRequestHeaders.Add("Accept", "*/*");
                c.DefaultRequestHeaders.Add("Connection", "keep-alive");

                Console.WriteLine("Finding req_id for login...");
                var initialResponse = await c.GetAsync("https://customer.xfinity.com/oauth/force_connect/?continue=%23%2Fdevices");

                Debug.Assert(initialResponse.StatusCode == HttpStatusCode.OK);
                var body = await initialResponse.Content.ReadAsStringAsync();

                var d = new HtmlAgilityPack.HtmlDocument();
                d.LoadHtml(body);
                var dd    = d.DocumentNode.Descendants("input");
                var reqId = dd.Where(n => n.Attributes.Contains("name") && n.Attributes["name"].Value == "reqId").FirstOrDefault()?.Attributes["value"]?.Value;

                Console.WriteLine("Found req_id = {0}", reqId);

                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("user", username),
                    new KeyValuePair <string, string>("passwd", password),
                    new KeyValuePair <string, string>("reqId", reqId),
                    new KeyValuePair <string, string>("deviceAuthn", "false"),
                    new KeyValuePair <string, string>("s", "oauth"),
                    new KeyValuePair <string, string>("forceAuthn", "1"),
                    new KeyValuePair <string, string>("r", "comcast.net"),
                    new KeyValuePair <string, string>("ipAddrAuthn", "false"),
                    new KeyValuePair <string, string>("Continue", "https://oauth.xfinity.com/oauth/authorize?client_id=my-account-web&prompt=login&redirect_uri=https%3A%2F%2Fcustomer.xfinity.com%2Foauth%2Fcallback&response_type=code&state=%23%2Fdevices&response=1"),
                    new KeyValuePair <string, string>("passive", "false"),
                    new KeyValuePair <string, string>("client_id", "my-account-web"),
                    new KeyValuePair <string, string>("lang", "en"),
                });
                var payload = content.ToString();

                Console.WriteLine("Posting to login...");
                var postResult = await c.PostAsync("https://login.xfinity.com/login", content);

                Debug.Assert(postResult.StatusCode == HttpStatusCode.OK);
                var postResponseContent = await postResult.Content.ReadAsStringAsync();

                Console.WriteLine("Fetching internet usage JSON...");
                var getResult = await c.GetAsync("https://customer.xfinity.com/apis/services/internet/usage");

                Debug.Assert(getResult.StatusCode == HttpStatusCode.OK);
                var datausage = await getResult.Content.ReadAsStringAsync();

                var usage = JsonConvert.DeserializeObject <DataUsage>(datausage);
                DisplayUsage(usage);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during operation: {0}", ex);
            }
        }