Exemplo n.º 1
0
        private static async void Foo()
        {
            Uri uri = new Uri("http://localhost/?cache=1");

            System.Net.Http.WebRequestHandler handler =
                new System.Net.Http.WebRequestHandler();

            // Cache options:
            //     System.Net.Cache.RequestCacheLevel.BypassCache
            //     System.Net.Cache.RequestCacheLevel.CacheIfAvailable
            handler.CachePolicy = new System.Net.Cache.RequestCachePolicy(
                System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

            System.Net.Http.HttpClient client2 =
                new System.Net.Http.HttpClient(handler);

            System.Net.Http.HttpResponseMessage response2 = await client2.GetAsync(uri);

            response2.EnsureSuccessStatusCode();
            string str = await response2.Content.ReadAsStringAsync();

            Console.WriteLine(str);

            System.Threading.Thread.Sleep(1111);

            response2 = await client2.GetAsync(uri);

            response2.EnsureSuccessStatusCode();
            str = await response2.Content.ReadAsStringAsync();

            Console.WriteLine(str);

            autoResetEvent.Set();
        }
Exemplo n.º 2
0
        public async Task <string> Post(string path, string payload, CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                throw new TaskCanceledException($"Post Request to {path} was cancelled");
            }
            string responseBody;

            // Call asynchronous network methods in a try/catch block to handle exceptions.
            try
            {
                // Console.WriteLine("    ... POST {0}", this.serverUri + path);
                var httpContent = new System.Net.Http.StringContent(payload, Encoding.UTF8, "application/json");
                System.Net.Http.HttpResponseMessage response = await this.client.PostAsync(this.serverUri + path, httpContent, token);

                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();

                //Console.WriteLine(responseBody);
            }
            catch (System.Net.Http.HttpRequestException e)
            {
                Console.WriteLine("\nUnexpected Server Error!");
                Console.WriteLine("Message :\n{0} ", e.Message);
                responseBody = "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n!!! [HttpClient.Post] UNEXPECTED EXCEPTION {0} !!!", ex.GetType().Name);
                throw;
            }
            return(responseBody);
        }
Exemplo n.º 3
0
        public async Task Get_get_all_catalogitems_and_response_ok_status_code()
        {
            using (Microsoft.AspNetCore.TestHost.TestServer server = CreateServer())
            {
                System.Net.Http.HttpResponseMessage response = await server.CreateClient()
                                                               .GetAsync(Get.Items());

                response.EnsureSuccessStatusCode();
            }
        }
Exemplo n.º 4
0
        public void Urls(string url)
        {
            TestUser user = Utils.DefaultUser;

            using (MockIdentityWebApplicationFactory id = new MockIdentityWebApplicationFactory(user))
            {
                using (System.Net.Http.HttpClient client = id.CreateClient())
                {
                    System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;
                    response.EnsureSuccessStatusCode();
                }
            }
        }
Exemplo n.º 5
0
        }     // End Task StartDownload

        protected async System.Threading.Tasks.Task DownloadFileFromHttpResponseMessage(
            System.Net.Http.HttpResponseMessage response
            )
        {
            response.EnsureSuccessStatusCode();

            long?totalBytes = response.Content.Headers.ContentLength;

            using (System.IO.Stream contentStream = await response.Content.ReadAsStreamAsync())
            {
                await ProcessContentStream(totalBytes, contentStream);
            } // End Using contentStream
        }     // End Task DownloadFileFromHttpResponseMessage
        public static void Main()
        {
            InitConfig();

            ClientCredential.AdhUri = new Uri(GetConfigValue("Resource"));

            string tenantId     = GetConfigValue("TenantId");
            string clientId     = GetConfigValue("ClientId");
            string clientSecret = GetConfigValue("ClientSecret");
            string version      = GetConfigValue("ApiVersion");

            ClientCredential.CreateAuthenticatedHttpClient(clientId, clientSecret);

            // Make an HTTP request to ADH using the authenticated client - since this is the first request, the AuthenticationHandler will
            // authenticate and acquire an Access Token and cache it.
            try
            {
                Uri uri = new ($"api/{version}/Tenants/{tenantId}/Users", UriKind.Relative);
                System.Net.Http.HttpResponseMessage response = ClientCredential.AuthenticatedHttpClient.GetAsync(uri).Result;
                response.EnsureSuccessStatusCode();
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.WriteLine($"HTTP GET api/{version}/Tenants/{tenantId}/Users successful");
            }
            catch (AggregateException ex)
            {
                foreach (Exception inEx in ex.Flatten().InnerExceptions)
                {
                    Console.WriteLine($"Authentication failed with the following error: {inEx.Message}");
                }

                throw;
            }

            // Make another request to ADH - this call should use the cached Access Token.
            try
            {
                Uri uri = new ($"api/{version}/Tenants/{tenantId}/Users", UriKind.Relative);
                System.Net.Http.HttpResponseMessage response = ClientCredential.AuthenticatedHttpClient.GetAsync(uri).Result;
                response.EnsureSuccessStatusCode();
                Console.WriteLine($"HTTP GET api/{version}/Tenants/{tenantId}/Users successful");
            }
            catch (AggregateException ex)
            {
                foreach (Exception inEx in ex.Flatten().InnerExceptions)
                {
                    Console.WriteLine($"Authentication failed with the following error: {inEx.Message}");
                }

                throw;
            }
        }
Exemplo n.º 7
0
        public async System.Threading.Tasks.Task <T> SendRequestAsync <T>(string requestMethod, string target, string jsonBody, int timeoutSeconds = 60)
        {
            System.Net.Http.HttpResponseMessage httpResponseMessage = await SendAsync(requestMethod, target, jsonBody, timeoutSeconds);

            System.Net.Http.HttpContent requestContent = httpResponseMessage.Content;
            string resultContent = requestContent.ReadAsStringAsync().Result;

#if DEBUG
            try
            {
                string tempDirectory  = System.IO.Path.GetTempPath();
                string targetFilename = string.Format("hrworks-dbg-{0}.json", target);
                string tempFilepath   = System.IO.Path.Combine(tempDirectory, targetFilename);

                string tmpContent = resultContent;

                try
                {
                    Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(tmpContent);
                    tmpContent = jsonResult.ToString(Newtonsoft.Json.Formatting.Indented);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                }


                System.IO.File.WriteAllText(tempFilepath, tmpContent);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
#endif
            try
            {
                httpResponseMessage.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                System.Net.Http.HttpRequestException httpRequestException = new System.Net.Http.HttpRequestException(resultContent, ex);
                throw httpRequestException;
            }

            System.Threading.Tasks.Task <T> typedResponse = System.Threading.Tasks.Task.Factory.StartNew(() => Newtonsoft.Json.JsonConvert.DeserializeObject <T>(resultContent));
            return(await typedResponse);
        }
Exemplo n.º 8
0
        public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
        {
            // Arrange
            AuthenticationManager authenticationManager = new AuthenticationManager();

            authenticationManager.client = _factory.CreateClient();
            File.WriteAllBytes("rsaCert.pfx", Startup.RsaCertPfxBytes);
            Chilkat.Pfx pfx = new Chilkat.Pfx();
            if (File.Exists("rsaCert.pfx"))
            {
                pfx.LoadPfxFile("rsaCert.pfx", "12345");
            }

            File.Delete("rsaCert.pfx");

            // Act
            //public key from certificate
            //Chilkat package is used to process X509 certificate 2 from pfx file to JWKS (Json Web Key Set) from which it is possible
            //to extract public key X5c. Key is then compared with the one pulled from mocked server.
            string alias    = "my_ecc_key1";
            string password = "******";

            Chilkat.JavaKeyStore  jks      = pfx.ToJavaKeyStore(alias, password);
            Chilkat.StringBuilder sbJwkSet = new Chilkat.StringBuilder();
            jks.ToJwkSet(password, sbJwkSet);
            Chilkat.JsonObject jwkSet = new Chilkat.JsonObject();
            jwkSet.LoadSb(sbJwkSet);
            jwkSet.EmitCompact = false;
            var               jwksCheck  = jwkSet.Emit();
            JsonWebKeySet     jwkscheck  = new JsonWebKeySet(jwksCheck);
            List <JsonWebKey> keyList2   = new List <JsonWebKey>(jwkscheck.Keys);
            string            publicKey2 = keyList2[0].X5c[0];

            //response from server
            System.Net.Http.HttpResponseMessage response = await authenticationManager.client.GetAsync(url);

            //public key from endpoint
            string publicKey = authenticationManager.GetPublicKey(url);

            // Assert
            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal(publicKey2, publicKey);
            authenticationManager.client.Dispose();
            _factory.Dispose();
        }
Exemplo n.º 9
0
        /// <summary>
        /// GET Data
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="data"></param>
        public static async Task <string> GETRequest(string httpAddress)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            string responseData = string.Empty;

            try {
                System.Net.Http.HttpResponseMessage response = await client.GetAsync(httpAddress);

                response.EnsureSuccessStatusCode();
                responseData = await response.Content.ReadAsStringAsync();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            } finally {
                client.Dispose();
            }

            return(responseData);
        }
        GetAsync <O>()
        {
            System.Net.Http.HttpResponseMessage response = null;

            try
            {
                response =
                    await
                    Http.GetAsync(requestUri : RequestUri);

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        O result =
                            await response.Content.ReadFromJsonAsync <O>();

                        return(result);
                    }
                    // When content type is not valid
                    catch (System.NotSupportedException)
                    {
                        System.Console.WriteLine("The content type is not supported.");
                    }
                    // Invalid JSON
                    catch (System.Text.Json.JsonException)
                    {
                        System.Console.WriteLine("Invalid JSON.");
                    }
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            finally
            {
                response.Dispose();
            }

            return(default);
Exemplo n.º 11
0
        private static String getDownloadUrl()
        {
            var handler = new System.Net.Http.HttpClientHandler();

            handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            var client = new System.Net.Http.HttpClient(handler);

            client.BaseAddress = new Uri("https://rpcs3.net/download");
            System.Net.Http.HttpResponseMessage response = client.GetAsync("").Result;
            response.EnsureSuccessStatusCode();
            string result = response.Content.ReadAsStringAsync().Result;
            //Console.WriteLine(result);

            int start = result.IndexOf("https://ci.");
            int end   = result.IndexOf("7z");

            result = result.Substring(start, (end - start) + 2);
            return(result);
        }
Exemplo n.º 12
0
        public async Task WhenConfigurePerTenantServicesHasAllValidArguments_ThenOk()
        {
            // Arrange
            WebHostBuilder builder = CreateWebHostBuilder <TestStartupValidArguments, TestTenant, TestTenantMemoryCacheResolver>();

            // Act
            using (TestServer server = new TestServer(builder))
                using (System.Net.Http.HttpClient client = server.CreateClient())
                {
                    System.Net.Http.HttpResponseMessage response = await client.GetAsync("/tenant-1-1").ConfigureAwait(false);

                    response.EnsureSuccessStatusCode();
                    string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    // Assert
                    Assert.Equal("Default", result);
                    builder = null;
                }
        }
Exemplo n.º 13
0
        /// <summary>
        /// POST Data
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="jsonData">POST Data</param>
        public static async Task <string> POSTRequest(string httpAddress, string jsonData)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            string responseData = string.Empty;

            try {
                System.Net.Http.HttpResponseMessage response = await client.PostAsync(httpAddress,
                                                                                      new System.Net.Http.StringContent(jsonData, Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();
                responseData = await response.Content.ReadAsStringAsync();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
                responseData = jsonData;
            } finally {
                client.Dispose();
            }

            return(responseData);
        }
Exemplo n.º 14
0
        /// <summary>
        /// 重新获取AccessToken
        /// </summary>
        private static void GetAccessToken()
        {
            try
            {
                //AccessToken
                System.Net.Http.HttpResponseMessage respAccessToken = HttpRequestHelper.HttpGetAsync(RequestAccessTokenUri).Result;
                respAccessToken.EnsureSuccessStatusCode();
                String  accessTokenContent = respAccessToken.Content.ReadAsStringAsync().Result;
                JObject jObjAccessToken    = Newtonsoft.Json.JsonConvert.DeserializeObject(accessTokenContent) as JObject;
                if (jObjAccessToken["access_token"] == null)
                {
                    throw new Exception(accessTokenContent);
                }
                _accessToken = jObjAccessToken["access_token"].ToString();
                expires_in   = jObjAccessToken["expires_in"].ToString();
                if (timer == null)
                {
                    Logger.WriteLogAsync("初始化Access_Token完成,Access_Token:" + AccessToken);
                }

                //JsApiTicket
                System.Net.Http.HttpResponseMessage respJsTicket = HttpRequestHelper.HttpGetAsync(RequestJsTicketUri).Result;
                respJsTicket.EnsureSuccessStatusCode();
                String  jsTicketContent = respJsTicket.Content.ReadAsStringAsync().Result;
                JObject jObjJsTicket    = Newtonsoft.Json.JsonConvert.DeserializeObject(jsTicketContent) as JObject;
                if (jObjJsTicket["ticket"] == null)
                {
                    throw new Exception(jsTicketContent);
                }
                _jsApiTicket = jObjJsTicket["ticket"].ToString();
                if (timer == null)
                {
                    Logger.WriteLogAsync("初始化JsApiTicket完成,JsApiTicket:" + _jsApiTicket);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLogAsync("初始化access_token失败,详情:" + ex.Message);
            }
        }
Exemplo n.º 15
0
    /// <summary>
    /// Http同步Post异步请求
    /// 参考地址    http://www.cnblogs.com/shanyou/archive/2012/03/21/2410739.html
    ///             http://www.tuicool.com/articles/rmiqYz
    ///             http://www.cnblogs.com/qingyuan/archive/2012/11/08/2760034.html
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData"></param>
    /// <param name="contentType"></param>
    public void HttpPostAsync(string url, string postData = "", string contentType = "application/json")
    {
        Encoding      encode = Encoding.UTF8;
        StringBuilder sb     = new StringBuilder();

        sb.AppendFormat("{0}", WebApiDomain);
        sb.AppendFormat("{0}", url);
        sb.AppendFormat("?appid={0}", AppId);
        url = sb.ToString();
        var sendData = encode.GetBytes(postData);

        System.Net.Http.HttpClient  httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpContent content    = new System.Net.Http.StringContent(postData);
        content.Headers.ContentType   = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
        content.Headers.ContentLength = sendData.Length;
        //通过HttpClient访问时如何指定返回格式
        //httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml");
        //httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json");
        //签名
        string token = auth.Generate(Common.Enum.HttpMethod.Post, url, AuthKey, postData);

        content.Headers.Add(auth.TokenName, token);
        //返回值
        //string retMessage = h.PostAsync(new Uri(url), content).Result.Content.ReadAsStringAsync().Result;
        httpClient.PostAsync(new Uri(url), content).ContinueWith(
            (requestTask) =>
        {
            //日志记录
            System.Net.Http.HttpResponseMessage response = requestTask.Result;
            System.Threading.Thread.Sleep(3000);
            // 确认响应成功,否则抛出异常
            response.EnsureSuccessStatusCode();
            // 异步读取响应为字符串
            //response.Content.ReadAsStringAsync().ContinueWith(
            //    (readTask) => Console.WriteLine(readTask.Result));
            //response.Content.ReadAsStringAsync().Result
        });
    }
Exemplo n.º 16
0
        public async Task WhenConfigurePerTenantServicesHasNonValidArguments_ThrowException()
        {
            // Arrange
            WebHostBuilder builder = CreateWebHostBuilder <TestStartup2, TestTenant, TestTenantMemoryCacheResolver>();

            // Act
            using (TestServer server = new TestServer(builder))
                using (System.Net.Http.HttpClient client = server.CreateClient())
                {
                    Task res() => Task.Run(async() =>
                    {
                        System.Net.Http.HttpResponseMessage response = await client.GetAsync("/tenant-1-1").ConfigureAwait(false);
                        response.EnsureSuccessStatusCode();
                        string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    });

                    Exception ex = await Assert.ThrowsAsync <InvalidOperationException>(res).ConfigureAwait(false);

                    Assert.Equal(
                        "The ConfigurePerTenantServices method must take only two parameter one of type IServiceCollection and one of type TTenant.",
                        ex.Message);
                }
        }
Exemplo n.º 17
0
        public async Task <List <NetiaApp> > GetAppsListAsync()
        {
            RootObject      rootObject = new RootObject();
            List <NetiaApp> appList    = new List <NetiaApp>();

            //http://epg.dms.netia.pl/xmltv/logo/black/netiaPadAppsSettings.json
            var address = "http://epg.dms.netia.pl/xmltv/logo/black/netiaPadAppsSettings.json";

            var uri = new Uri(address, UriKind.Absolute);


            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
                try
                {
                    System.Net.Http.HttpResponseMessage response = await client.GetAsync(uri);

                    response.EnsureSuccessStatusCode();
                    var data = await response.Content.ReadAsStringAsync();

                    rootObject = JsonConvert.DeserializeObject <RootObject>(data);

                    appList = enumrateRootObjectApps(rootObject);

                    return(appList);
                }
                catch (Exception)
                {
                    return(appList);;     //empty
                }
            }
        }
Exemplo n.º 18
0
        public async Task <TvChannels> GetCurrentChanellInfoAsync()
        {
            TvChannels currentChannel = new TvChannels();
            string     address        = String.Empty;

            if (!string.IsNullOrWhiteSpace(_ipAddress))
            {
                //http://192.168.1.4/Live/Channels/getCurrent
                address = "http://" + _ipAddress + "/Live/Channels/getCurrent";

                var uri = new Uri(address, UriKind.Absolute);
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
                    try
                    {
                        System.Net.Http.HttpResponseMessage response = await client.GetAsync(uri);

                        response.EnsureSuccessStatusCode();
                        var data = await response.Content.ReadAsStringAsync();

                        currentChannel = JsonConvert.DeserializeObject <TvChannels>(data);

                        return(currentChannel);
                    }
                    catch (Exception)
                    {
                        return(currentChannel);
                    }
                }
            }
            return(currentChannel);
        }
Exemplo n.º 19
0
        GetAsync <TResponse>(string url, string query = null)
        {
            System.Net.Http.HttpResponseMessage response = null;

            try
            {
                string requestUri =
                    $"{ BaseUrl }/{ url }";

                if (string.IsNullOrWhiteSpace(query) == false)
                {
                    requestUri =
                        $"{ requestUri }?{ query }";
                }

                response =
                    await
                    Http.GetAsync
                        (requestUri : requestUri)
                ;

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        // ReadFromJsonAsync -> Extension Method -> using System.Net.Http.Json;
                        TResponse result =
                            await
                            response.Content.ReadFromJsonAsync <TResponse>();

                        return(result);
                    }

                    // When content type is not valid
                    catch (System.NotSupportedException)
                    {
                        System.Console.WriteLine("The content type is not supported.");
                    }

                    // Invalid JSON
                    catch (System.Text.Json.JsonException)
                    {
                        System.Console.WriteLine("Invalid JSON.");
                    }
                }
            }

            catch (System.Net.Http.HttpRequestException ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            finally
            {
                response.Dispose();
                //response = null;
            }

            return(default);
        static void Main(string[] args)
        {
            try
            {
                System.Console.WriteLine("NETCore.TestFirstDataMicroIndicatorService running....");

                // use TLS 1.2. Note that Telecheck MI REST/JSON documentation only specifies use of SHA256 certificates, but TLS 1.2 is most recent standard
                // this is a static or global setting for the network security protocol to use... why not put this setting on the actual client?
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                System.Security.Cryptography.X509Certificates.X509Certificate2 x509Cert = null;
                x509Cert = FindCertByThumbprint("8e00205e0b8b567d720fea44059c391d4bfaf7ed", System.Security.Cryptography.X509Certificates.StoreName.TrustedPeople, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, true);

                System.Net.Http.HttpClientHandler someHttpHandler = new System.Net.Http.HttpClientHandler();
                someHttpHandler.ClientCertificates.Add(x509Cert);
                // see Appendix H in "TELECHECK NEW ACCOUNT SCREENING AND CONFIDENT SCORING AND MICRO INDICATORS DIAL AND LINK AND WEB SPECIFICATION"
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(someHttpHandler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Connection", "keep-alive");    // instruct server to close or keep-alive - we request keep-alive

                    var localTime        = DateTime.Now;
                    var utcTime          = localTime.ToUniversalTime();
                    var formattedUtcTime = utcTime.ToString("yyyy-MM-ddThh:mm:ssZ");

                    // compose request
                    var microIndicatorRequest = new
                    {
                        merchantId = "26008392", // DevWire
                        //merchantId = "26008655", // CheckCity

                        versionControl       = "DRAGNETNAS 20120830 WIN7 SNNK 000",
                        micr                 = "181210002484143878114", // 18 + routing number + account number (no spaces)
                        amount               = "1.00",
                        dateTime             = formattedUtcTime,
                        teleCheckProductName = "NEW_ACCT"
                    };

                    // convert request to JSON
                    string jsonMicroIndicatorRequest = JsonConvert.SerializeObject(microIndicatorRequest).ToString();
                    var    content = new System.Net.Http.StringContent(jsonMicroIndicatorRequest, System.Text.Encoding.UTF8, "application/json");

                    // POST request to First Data microindicator service
                    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                    sw.Start();

                    // don't block on async code
                    // see http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
                    // see http://stackoverflow.com/questions/26597665/how-to-get-content-body-from-a-httpclient-call
                    var url = "https://api.telecheck.com/v1/TckWS/Authorization";

                    System.Net.Http.HttpResponseMessage rawHttpResponse = null;

                    Console.WriteLine("Sending....");                        // gratuitous change #2 to test GitHub source code control
                    Console.WriteLine("Still Sending....");                  // gratuitous change #3 to test GitHub source code control

                    Console.WriteLine("Branch1 - Still sending....");        // code change on Branch1
                    Console.WriteLine("Branch1 - code change 2");            // 2nd code change on Branch1

                    rawHttpResponse = client.PostAsync(url, content).Result; // configure the Client to not capture current context, returning on a Thread Pool thread, avoiding deadlocks
                    rawHttpResponse.EnsureSuccessStatusCode();               // EnsureSuccess is preferred, will generate exception on non-success


                    sw.Stop();

                    if (rawHttpResponse.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        // convert response to JSON
                        dynamic microIndicatorResponse = JsonConvert.DeserializeObject <dynamic>(
                            rawHttpResponse.Content.ReadAsStringAsync().Result);  // Result property blocks calling thread until task finishes

                        // dump response
                        Console.WriteLine(microIndicatorResponse.ToString());
                        Console.WriteLine();
                        Console.WriteLine("Elapsed Time: {0} ms", sw.ElapsedMilliseconds);
                    }
                    else
                    {
                        // dump error response
                        var errorResponse = rawHttpResponse.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(errorResponse);
                        Console.WriteLine();
                        Console.WriteLine("Elapsed Time: {0} ms", sw.ElapsedMilliseconds);
                    }
                } // end using block



                //System.Net.Http.HttpClient theHttpClient = new System.Net.Http.HttpClient();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine();
                System.Console.WriteLine(ex.Message);
            }

            System.Console.WriteLine();
            System.Console.WriteLine("Press any key to exit...");
            System.Console.ReadLine();
        }
        private async void TranslateText()
        {
            if (InputTextBox.Text == String.Empty)
            {
                MessageBox.Show("Input text is empty.");
                return;
            }

            try
            {
                TranslateButton.Content = new ProgressBar()
                {
                    IsIndeterminate = true
                };;

                using (System.Net.Http.StringContent httpContent = new System.Net.Http.StringContent($"text={InputTextBox.Text}", Encoding.UTF8, CONTENT_TYPE_HEADER))
                {
                    System.Net.Http.HttpResponseMessage responseTypeLang = await HttpClient.PostAsync(
                        $"https://translate.yandex.net/api/v1.5/tr.json/detect?hint={EN_LANG_DIR},{RU_LANG_DIR}&key={API_KEY}", httpContent
                        );

                    responseTypeLang.EnsureSuccessStatusCode();
                    String responseTypeLangBody = await responseTypeLang.Content.ReadAsStringAsync();

                    Dictionary <String, String> responseTypeLangDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <String, String> >(responseTypeLangBody);
                    String codeTypeLangValue = null;
                    responseTypeLangDict.TryGetValue("code", out codeTypeLangValue);


                    if (codeTypeLangValue == "200")
                    {
                        String langValue = null;
                        responseTypeLangDict.TryGetValue("lang", out langValue);

                        SetInputLang(langValue);
                    }
                    else
                    {
                        throw new Exception();
                    }
                }

                using (System.Net.Http.StringContent httpContent = new System.Net.Http.StringContent($"text={InputTextBox.Text}", Encoding.UTF8, CONTENT_TYPE_HEADER))
                {
                    String langDirection = m_currentInputLang == EnInputLang.RUSSIAN ? "ru-en" : "en-ru"; // en-ru -> in-out
                    System.Net.Http.HttpResponseMessage responseTranslatedText = await HttpClient.PostAsync(
                        $"https://translate.yandex.net/api/v1.5/tr.json/translate?lang={langDirection}&key={API_KEY}&format=plain", httpContent
                        );

                    responseTranslatedText.EnsureSuccessStatusCode();
                    String responseTranslatedTextBody = await responseTranslatedText.Content.ReadAsStringAsync();

                    Dictionary <String, Object> responseTranslatedTextDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <String, Object> >(responseTranslatedTextBody);
                    Object codeTranslatedTextValue = null;
                    responseTranslatedTextDict.TryGetValue("code", out codeTranslatedTextValue);

                    if ((Int64)codeTranslatedTextValue == 200)
                    {
                        var textArray = (Newtonsoft.Json.Linq.JArray)responseTranslatedTextDict["text"];
                        OutputTextBox.Text = textArray.First.ToString();
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
            catch (System.Net.Http.HttpRequestException e)
            {
                MessageBox.Show($"Error Message: {e.Message}");
                return;
            }
            catch (Exception e) {
                MessageBox.Show($"Error Message: {e.Message}");
                return;
            }
            finally
            {
                TranslateButton.Content = "Translate";
            }

            UpdateCountSymbolsOutputText();
            SetStatus();
        }
Exemplo n.º 22
0
        public async Task <List <TvChannels> > GetChannelListAsync()
        {
            List <TvChannels> tvChannelList = new List <TvChannels>();
            string            address       = String.Empty;

            if (!string.IsNullOrWhiteSpace(_ipAddress))
            {
                address = "http://" + _ipAddress + "/Live/Channels/getList";

                var uri = new Uri(address, UriKind.Absolute);


                #region different way to send httpClient
                //using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                //{
                //    try
                //    {

                //        var headers = httpClient.DefaultRequestHeaders;

                //        headers.UserAgent.ParseAdd(
                //            "Netia%C2%A0Player%C2%A0Pilot/2014.10.271657 CFNetwork/758.1.6 Darwin/15.0.0");


                //        var content = await httpClient.GetStreamAsync(uri);

                //        //var content = await httpClient.GetStringAsync(uri);

                //        var intt = content.Length;

                //        tvChannelList = JsonConvert.DeserializeObject<List<TvChannels>>(content.ToString());

                //        return tvChannelList;

                //    }
                //    catch (Exception ex)
                //    {

                //    }
                //}
                #endregion

                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
                    try
                    {
                        System.Net.Http.HttpResponseMessage response = await client.GetAsync(uri);

                        response.EnsureSuccessStatusCode();
                        var data = await response.Content.ReadAsStringAsync();

                        tvChannelList = JsonConvert.DeserializeObject <List <TvChannels> >(data);

                        return(tvChannelList);
                    }
                    catch (Exception)
                    {
                        return(tvChannelList);
                    }
                }
            }
            return(tvChannelList);
        }
        private  void GetCountsFromWeb(ref webResults VoteColorPair)
        {
            //Create an HTTP client object
            // Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            System.Net.Http.HttpClient snhClient = new System.Net.Http.HttpClient();
            //Add a user-agent header to the GET request. 
            var headers = snhClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri(RestUrlBox.Text);

            //Send the GET request asynchronously and retrieve the response as a string.
            System.Net.Http.HttpResponseMessage snhResponse = new System.Net.Http.HttpResponseMessage();
   
           // Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                int Reds = -1;
                int Blues = -1;

                //Send the GET request
                snhResponse = snhClient.GetAsync(requestUri).Result;
                //httpResponse =  await httpClient.GetAsync(requestUri,Windows.Web.Http.HttpCompletionOption.ResponseContentRead).Re;
                snhResponse.EnsureSuccessStatusCode();
                //httpResponse.EnsureSuccessStatusCode();
                //httpResponseBody = httpResponse.Content.ToString();
                httpResponseBody = snhResponse.Content.ReadAsStringAsync().Result;
                debugText.Text += httpResponseBody;
                int blueCloseCurlyLoc = httpResponseBody.IndexOf("}");
                string bluestring = httpResponseBody.Substring(0, blueCloseCurlyLoc);
                int lastColonLoc = bluestring.LastIndexOf(":");
                bluestring = bluestring.Substring(lastColonLoc+1, blueCloseCurlyLoc - lastColonLoc-1);
                Blues = int.Parse(bluestring);

                int redCloseCurlyLoc = httpResponseBody.LastIndexOf("}");
                string redstring = httpResponseBody.Substring(blueCloseCurlyLoc+1, redCloseCurlyLoc - blueCloseCurlyLoc);
                lastColonLoc = redstring.LastIndexOf(":");
                redCloseCurlyLoc = redstring.LastIndexOf("}");
                redstring = redstring.Substring(lastColonLoc + 1, redCloseCurlyLoc - lastColonLoc - 1);
                Reds = int.Parse(redstring);

                /*                JObject voteJson = JObject.Parse(httpResponseBody);
                if (voteJson[0]["Color"].ToString() == "Blue")
                {
                    Blues = int.Parse(voteJson[0]["Count"].ToString());
                }
                if (voteJson[1]["Color"].ToString() == "Red")
                {
                    Reds = int.Parse(voteJson[1]["Count"].ToString());
                }
*/

                VoteColorPair.RedVotes = Reds;
                VoteColorPair.BlueVotes = Blues;
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                debugText.Text = httpResponseBody;
            }


        }
        GetAsync <TResponse>(string url, string query = null)
        {
            System.Net.Http.HttpResponseMessage response = null;

            try
            {
                string requestUri =
                    $"{ BaseUrl }/{ url }";

                if (string.IsNullOrWhiteSpace(query) == false)
                {
                    requestUri =
                        $"{ requestUri }?{ query }";
                }

                response =
                    await
                    Http.GetAsync
                        (requestUri : requestUri)
                ;

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        // ReadFromJsonAsync -> Extension Method -> using System.Net.Http.Json;
                        TResponse result =
                            await
                            response.Content.ReadFromJsonAsync <TResponse>();

                        return(result);
                    }

                    // When content type is not valid
                    catch (System.NotSupportedException ex)
                    {
                        string errorMessage =
                            $"Exception: { ex.Message } - The content type is not supported.";

                        // Static داخل تابع غیر
                        LogsService.AddLog(type: GetType(), message: errorMessage);

                        // Static داخل تابع
                        //LogsService.AddLog(type: typeof(ServiceBase), message: errorMessage);
                    }

                    // Invalid JSON
                    catch (System.Text.Json.JsonException ex)
                    {
                        string errorMessage =
                            $"Exception: { ex.Message } - Invalid JSON.";

                        LogsService.AddLog(type: GetType(), message: errorMessage);
                    }
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                string errorMessage =
                    $"Exception: { ex.Message }";

                LogsService.AddLog(type: GetType(), message: errorMessage);
            }
            finally
            {
                response.Dispose();
            }

            return(default);