当前位置: 首页>>代码示例>>C#>>正文


C# HttpClient.SendAsync方法代码示例

本文整理汇总了C#中System.Net.Http.HttpClient.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.SendAsync方法的具体用法?C# HttpClient.SendAsync怎么用?C# HttpClient.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpClient的用法示例。


在下文中一共展示了HttpClient.SendAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ChangeUserProfile

        public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
            UserAccountEntity userAccountEntity)
        {
            if (userAccountEntity.GetAccessToken().Equals("refresh"))
            {
                await Auth.RefreshAccessToken(userAccountEntity);
            }
            var param = new Dictionary<String, String>();
            if (!string.IsNullOrEmpty(name)) param.Add("name", name);
            if (!string.IsNullOrEmpty(url)) param.Add("url", url);
            if (!string.IsNullOrEmpty(location)) param.Add("location", location);
            if (!string.IsNullOrEmpty(description)) param.Add("description", description);

            var theAuthClient = new HttpClient();
            HttpContent header = new FormUrlEncodedContent(param);
            var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
            try
            {
                HttpResponseMessage response = await theAuthClient.SendAsync(request);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:happy-ryo,项目名称:CrouMetro,代码行数:27,代码来源:UserManager.cs

示例2: Translate

        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
开发者ID:rhysgodfrey,项目名称:Trosi,代码行数:31,代码来源:Translator.cs

示例3: AttriubteRouting_SelectsExpectedControllerAndAction

        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
开发者ID:richarddwelsh,项目名称:aspnetwebstack,代码行数:33,代码来源:AttributeRoutingTest.cs

示例4: Mvc200RequestFW45BasicRequestSyntheticFiltering

        public void Mvc200RequestFW45BasicRequestSyntheticFiltering()
        {
            const string requestPath = "api/products";
            const string expectedRequestName = "GET products";
            string expectedRequestUrl = this.Config.ApplicationUri + "/" + requestPath;

            DateTimeOffset testStart = DateTimeOffset.UtcNow;

            //Call an applicaiton page
            var client = new HttpClient();
            var requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(expectedRequestUrl),
                Method = HttpMethod.Get,
            };

            requestMessage.Headers.Add("User-Agent", "bingbot");

            var responseTask = client.SendAsync(requestMessage);
            responseTask.Wait(TimeoutInMs);
            var responseTextTask = responseTask.Result.Content.ReadAsStringAsync();
            responseTextTask.Wait(TimeoutInMs);
            Assert.IsTrue(responseTextTask.Result.StartsWith("[{"));

            var request = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(1, TimeoutInMs)[0];

            var testFinish = DateTimeOffset.UtcNow;

            this.TestWebApplicationHelper(expectedRequestName, expectedRequestUrl, "200", true, request, testStart, testFinish);
            Assert.AreEqual("Spider", request.OperationContext.SyntheticSource);
        }
开发者ID:jawn,项目名称:ApplicationInsights-server-dotnet,代码行数:31,代码来源:WebAppFW45Tests.cs

示例5: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var req1 = new HttpRequestMessage(HttpMethod.Get, address + "order/1");
                var res1 = client.SendAsync(req1).Result;
                Console.WriteLine(req1.RequestUri);
                Console.WriteLine(res1.Content.ReadAsStringAsync().Result);

                Console.WriteLine();

                var req2 = new HttpRequestMessage(HttpMethod.Get, address + "auftrag/1");
                var res2 = client.SendAsync(req2).Result;
                Console.WriteLine(req2.RequestUri);
                Console.WriteLine(res2.Content.ReadAsStringAsync().Result);

                Console.WriteLine();

                var req3 = new HttpRequestMessage(HttpMethod.Get, address + "zamowienie/1");
                var res3 = client.SendAsync(req3).Result;
                Console.WriteLine(req3.RequestUri);
                Console.WriteLine(res3.Content.ReadAsStringAsync().Result);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:30,代码来源:Program.cs

示例6: UserCredentialsPopsDialog

        public void UserCredentialsPopsDialog()
        {
            var cache = new TestTokenCache();
            var settings = ActiveDirectoryServiceSettings.Azure;
            var credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, 
                ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), 
                settings, this._username, cache).GetAwaiter().GetResult();
            var client = new HttpClient();

            var request = new HttpRequestMessage(HttpMethod.Get,
                new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));
            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Repeat with PromptBehavior.Never
             credentials = UserTokenProvider.LoginWithPromptAsync(this._domain, 
                 ActiveDirectoryClientSettings.UseCacheOrCookiesOnly("1950a258-227b-4e31-a9cf-717495945fc2",new Uri("urn:ietf:wg:oauth:2.0:oob")), 
                 settings, this._username, cache).GetAwaiter().GetResult();
            request = new HttpRequestMessage(HttpMethod.Get,
                new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));
            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Repeat with getting tokens strictly from cache
            credentials = UserTokenProvider.CreateCredentialsFromCache("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, cache).GetAwaiter().GetResult();
            request = new HttpRequestMessage(HttpMethod.Get,
                new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview"));
            credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait();
            Assert.NotNull(request.Headers.Authorization);
            response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
      }
开发者ID:tonytang-microsoft-com,项目名称:autorest,代码行数:34,代码来源:ActiveDirectoryCredentialsTest.cs

示例7: RemoteEndpoint

        protected RemoteEndpoint(string protocol, string server, int regularPort, int adminPort)
        {
            var builder = new UriBuilder();
            builder.Scheme = protocol;
            builder.Host = server;
            builder.Port = regularPort;
            _regularUri = builder.Uri;

            builder.Port = adminPort;
            _adminUri = builder.Uri;

            using (var httpClient = new HttpClient()) {
                try {
                    var request = new HttpRequestMessage(HttpMethod.Get, _adminUri + "/");
                    var response = httpClient.SendAsync(request).Result;
                    request = new HttpRequestMessage(HttpMethod.Get, _regularUri + "/");
                    response = httpClient.SendAsync(request).Result;
                } catch(AggregateException e) {
                    var ex = e.InnerException as WebException;
                    if (ex != null && ex.Status == WebExceptionStatus.ConnectFailure) {
                        Assert.Inconclusive("Failed to get connection to {0}", Type);
                    }
                }
            }
        }
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:25,代码来源:RemoteEndpoint.cs

示例8: GlimpseTweets

        [OutputCache(Duration = 3600)] // Cache for 1 hour
        public virtual async Task<ActionResult> GlimpseTweets()
        {
            var key = ConfigurationManager.AppSettings["TwitterKey"];
            var secret = ConfigurationManager.AppSettings["TwitterSecret"];
            var bearerToken = GetBearerTokenCredentials(key, secret);

            var httpClient = new HttpClient();

            var accessTokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token");
            accessTokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", bearerToken);
            accessTokenRequest.Headers.Accept.ParseAdd("application/x-www-form-urlencoded;charset=UTF-8");
            accessTokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "grant_type", "client_credentials" }
                });

            var accessTokenResponse = await httpClient.SendAsync(accessTokenRequest);
            accessTokenResponse.EnsureSuccessStatusCode();
            var jsonString = await accessTokenResponse.Content.ReadAsStringAsync();
            dynamic json = JObject.Parse(jsonString);
            string accessToken = json.access_token;

            var query = "from:@nikmd23 OR from:@anthony_vdh OR from:@CGijbels #glimpse";
            var searchRequest = new HttpRequestMessage(HttpMethod.Get, "https://api.twitter.com/1.1/search/tweets.json?q=" + HttpUtility.UrlEncode(query));
            searchRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var searchResponse = await httpClient.SendAsync(searchRequest);
            searchResponse.EnsureSuccessStatusCode();
            var result = await searchResponse.Content.ReadAsStringAsync();

            return Content(result, "application/json");
        }
开发者ID:Noer024,项目名称:Glimpse.Site,代码行数:32,代码来源:HomeController.cs

示例9: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                PrintResponse(client.GetAsync(address + "api/items.json").Result);
                PrintResponse(client.GetAsync(address + "api/items.xml").Result);

                PrintResponse(client.GetAsync(address + "api/items?format=json").Result);
                PrintResponse(client.GetAsync(address + "api/items?format=xml").Result);

                var message1 = new HttpRequestMessage(HttpMethod.Get, address + "api/items");
                message1.Headers.Add("ReturnType","json");
                var message2 = new HttpRequestMessage(HttpMethod.Get, address + "api/items");
                message2.Headers.Add("ReturnType", "xml");

                PrintResponse(client.SendAsync(message1).Result);
                PrintResponse(client.SendAsync(message2).Result);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:25,代码来源:Program.cs

示例10: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();
                
                var normalRequest = new HttpRequestMessage(HttpMethod.Get, address + "items");
                Console.WriteLine(normalRequest);
                var normalResponse = client.SendAsync(normalRequest).Result;
                Console.WriteLine(normalResponse);
                Console.WriteLine(normalResponse.Content.ReadAsStringAsync().Result);

                Console.WriteLine();
                Console.WriteLine();

                var rangeRequest = new HttpRequestMessage(HttpMethod.Get, address + "items");
                rangeRequest.Headers.Range = new RangeHeaderValue(from: 2, to: 4)
                {
                    Unit = "Item"
                };
                Console.WriteLine(rangeRequest);
                var rangeResponse = client.SendAsync(rangeRequest).Result;
                Console.WriteLine(rangeResponse);
                Console.WriteLine(rangeResponse.Content.ReadAsStringAsync().Result);

                Console.ReadLine();
            }
        } 
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:30,代码来源:Program.cs

示例11: Main

        static void Main()
        {
            var address = "http://localhost:9000/";
            var files = new[]
            {
                Path.Combine(Assembly.GetExecutingAssembly().Location, @"..\..\..\textfile.txt"),
                Path.Combine(Assembly.GetExecutingAssembly().Location, @"..\..\..\evilfile.bat")
            };

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var message1 = new HttpRequestMessage(HttpMethod.Post, address + "upload")
                {
                    Content = GetContentToUpload(files)
                };

                var result1 = client.SendAsync(message1).Result;
                Console.WriteLine(result1.StatusCode);

                Console.WriteLine();

                var message2 = new HttpRequestMessage(HttpMethod.Post, address + "uploadToMemory")
                {
                    Content = GetContentToUpload(files)
                };

                var result2 = client.SendAsync(message2).Result;
                Console.WriteLine(result2.Content.ReadAsStringAsync().Result);
                Console.WriteLine(result2.StatusCode);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:35,代码来源:Program.cs

示例12: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var message1 = new HttpRequestMessage(HttpMethod.Post, address + "buffered")
                {
                    Content = GetContentToUpload()
                };

                var result1 = client.SendAsync(message1).Result;
                Console.WriteLine(result1.Content.ReadAsStringAsync().Result);
                Console.WriteLine(result1.StatusCode);

                Console.WriteLine();

                var message2 = new HttpRequestMessage(HttpMethod.Post, address + "unbuffered")
                {
                    Content = GetContentToUpload()
                };

                var result2 = client.SendAsync(message2).Result;
                Console.WriteLine(result2.Content.ReadAsStringAsync().Result);
                Console.WriteLine(result2.StatusCode);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:31,代码来源:Program.cs

示例13: Download

 public bool Download(Uri torrent, Uri torrenWebUiUri, string password)
 {
     using (var client = new HttpClient())
     {
         var request = new HttpRequestMessage(HttpMethod.Post, $"{torrenWebUiUri}login");
         var formContent = new List<KeyValuePair<string, string>>
         {
             new KeyValuePair<string, string>("username", "admin"),
             new KeyValuePair<string, string>("password", password)
         };
         request.Content = new FormUrlEncodedContent(formContent);
         var responseContent = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
         if (!responseContent.Equals(SuccessAuthResponse))
         {
             _logger.Error($"{GetType().Name}: Invalid login or password");
             return false;
         }
         request = new HttpRequestMessage(HttpMethod.Post, $"{torrenWebUiUri}command/download");
         formContent = new List<KeyValuePair<string, string>>
         {
             new KeyValuePair<string, string>("urls", torrent.AbsoluteUri)
         };
         request.Content = new FormUrlEncodedContent(formContent);
         responseContent = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
     }
     return true;
 }
开发者ID:u2718,项目名称:HousewifeBot,代码行数:27,代码来源:QBittorrentDownloader.cs

示例14: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var message1 = new HttpRequestMessage(HttpMethod.Get, address + "test1");
                var response1 = client.SendAsync(message1).Result;

                Console.WriteLine(response1.Content.ReadAsStringAsync().Result);
                Console.WriteLine();

                var message2 = new HttpRequestMessage(HttpMethod.Get, address + "test2");
                var response2 = client.SendAsync(message2).Result;

                Console.WriteLine(response2.Content.ReadAsStringAsync().Result);
                Console.WriteLine();

                var message3 = new HttpRequestMessage(HttpMethod.Get, address + "test3");
                var response3 = client.SendAsync(message3).Result;

                Console.WriteLine(response3.Content.ReadAsStringAsync().Result);
            }

            Console.ReadLine();
        } 
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:28,代码来源:Program.cs

示例15: DoSyncRequest

 public ElasticsearchResponse DoSyncRequest(string method, Uri uri, byte[] data = null)
 {
     var client = new System.Net.Http.HttpClient();
     HttpResponseMessage response = null;
     byte[] result = null;
     HttpContent content = null;
     if (data != null)
         content = new ByteArrayContent(data);
     switch (method.ToLower())
     {
         case "head":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri) ).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "delete":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri) { Content = content }).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "put":
             response = client.PutAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "post":
             response = client.PostAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "get":
             response = client.GetAsync(uri).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
     }
     return ElasticsearchResponse.Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result);
 }
开发者ID:kowalot,项目名称:elasticsearch-net,代码行数:33,代码来源:ElasticsearchHttpClient.cs


注:本文中的System.Net.Http.HttpClient.SendAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。