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


C# HttpClient.GetAsync方法代码示例

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


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

示例1: ThresholdExceeded_ThrowsException

        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                s.Listen(1);
                var ep = (IPEndPoint)s.LocalEndPoint;

                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead);

                    using (Socket server = s.Accept())
                    using (Stream serverStream = new NetworkStream(server, ownsSocket: false))
                    using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                        byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                        serverStream.Write(headerData, 0, headerData.Length);
                    }

                    if (shouldSucceed)
                    {
                        (await getAsync).Dispose();
                    }
                    else
                    {
                        await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                    }
                }
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:35,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例2: LogOnAsync

        public async Task<LogOnResult> LogOnAsync(string userId, string password)
        {
            using (var client = new HttpClient())
            {
                // Ask the server for a password challenge string
                var requestId = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.GenerateRandom(4));
                var challengeResponse = await client.GetAsync(new Uri(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId));
                challengeResponse.EnsureSuccessStatusCode();
                var challengeEncoded = await challengeResponse.Content.ReadAsStringAsync();
                challengeEncoded = challengeEncoded.Replace(@"""", string.Empty);
                var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded);

                // Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key.
                var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512);
                var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
                var hmacKey = provider.CreateKey(passwordBuffer);
                var buffHmac = CryptographicEngine.Sign(hmacKey, challengeBuffer);
                var hmacString = CryptographicBuffer.EncodeToHexString(buffHmac);

                // Send the encoded challenge to the server for authentication (to avoid sending the password itself)
                var response = await client.GetAsync(new Uri(_clientBaseUrl + userId + "?requestID=" + requestId + "&passwordHash=" + hmacString));

                // Raise exception if sign in failed
                response.EnsureSuccessStatusCode();

                // On success, return sign in results from the server response packet
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<UserInfo>(responseContent);
                var serverUri = new Uri(Constants.ServerAddress);
                return new LogOnResult { UserInfo = result };
            }
        }
开发者ID:CruzerBoon,项目名称:Prism-Samples-Windows,代码行数:32,代码来源:IdentityServiceProxy.cs

示例3: SendGetRequest

		static public async Task<string> SendGetRequest ( string address )
		{
			var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
			httpFilter.CacheControl.ReadBehavior =
				Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
			httpClient = new HttpClient ( httpFilter );
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//get
			try
			{
				response = await httpClient.GetAsync ( resourceUri );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
开发者ID:tranchikhang,项目名称:BookShare,代码行数:35,代码来源:RestAPI.cs

示例4: GetActvityDataAsync

		private static async Task<ObservableCollection<Activity>> GetActvityDataAsync(int locationId = 0, int profileId = 0) {
			var activities = new ObservableCollection<Activity>();

			using (var httpClient = new HttpClient()) {
				var apiKey = Common.StorageService.LoadSetting("ApiKey");
				var apiUrl = Common.StorageService.LoadSetting("ApiUrl");

				httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
				httpClient.DefaultRequestHeaders.Add("token", apiKey);
				httpClient.DefaultRequestHeaders.Add("api-version", "2");

				try {
					var url = apiUrl + "/api/activity";
					if (locationId > 0) {
						url = url + "/location/" + locationId.ToString();
					}
					if (profileId > 0) {
						url = url + "/profile/" + profileId.ToString();
					}

					var httpResponse = await httpClient.GetAsync(new Uri(url));
					string json = await httpResponse.Content.ReadAsStringAsync();
					json = json.Replace("<br>", Environment.NewLine);
					activities = JsonConvert.DeserializeObject<ObservableCollection<Activity>>(json);
				}
				catch (Exception e) { }
			}

			return activities;
		}
开发者ID:wvannigtevegt,项目名称:S2M_UWP,代码行数:30,代码来源:Activity.cs

示例5: GetTextByGet

 public static async Task<string> GetTextByGet(string posturi)
 {
     var httpClient = new HttpClient();
     var response = await httpClient.GetAsync(new Uri(posturi));
     string responseString = await response.Content.ReadAsStringAsync();
     return responseString;
 }
开发者ID:startewho,项目名称:SLWeek,代码行数:7,代码来源:HttpHelper.cs

示例6: Execute

        public async void Execute(string token, string content)
        {
            Uri uri = new Uri(API_ADDRESS + path);

            var rootFilter = new HttpBaseProtocolFilter();

            rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

            HttpClient client = new HttpClient(rootFilter);
            //client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString());
            if(token != null)
                client.DefaultRequestHeaders.Add("x-access-token", token);

            System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);

            HttpResponseMessage response = null;
            if (requestType == GET)
            {
                try
                {
                    response = await client.GetAsync(uri).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }

            }else if (requestType == POST)
            {
                HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri);
                if (content != null)
                {
                    msg.Content = new HttpStringContent(content);
                    msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                }

                try
                {
                    response = await client.SendRequestAsync(msg).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }
            }

            if (response == null)
            {
                if (listener != null)
                    listener.onTaskCompleted(null, requestCode);
            }
            else
            {
                string answer = await response.Content.ReadAsStringAsync();

                if(listener != null)
                    listener.onTaskCompleted(answer, requestCode);
            }
        }
开发者ID:francisco-maciel,项目名称:FEUP-CMOV_StockQuotes,代码行数:60,代码来源:APIRequest.cs

示例7: getRecipe

        public async Task<Model.Recipef2f> getRecipe(String recipeId)
        {
            var httpClient = new HttpClient();
            var uri = new Uri(stringUri+recipeId);

            HttpResponseMessage result = await httpClient.GetAsync(uri);

            Model.Recipef2f recipe = new Model.Recipef2f();

            JsonObject jsonObject = JsonObject.Parse(result.Content.ToString());

            JsonObject jsonValue = jsonObject.GetNamedObject("recipe", new JsonObject());
            
            recipe.Publisher = jsonValue.GetNamedString("publisher", "");
            recipe.F2fUrl = jsonValue.GetNamedString("f2f_url", "");
            JsonArray ingredientsArray = jsonValue.GetNamedArray("ingredients");
            foreach(JsonValue ingredient in ingredientsArray)
            {
                recipe.IngredientsList += ingredient.ToString() + " \n ";
            } 
            recipe.SourceUrl = jsonValue.GetNamedString("source_url", "");
            recipe.ImageUrl = jsonValue.GetNamedString("image_url", "");
            recipe.SocialRank = jsonValue.GetNamedNumber("social_rank", 0);
            recipe.PublisherUrl = jsonValue.GetNamedString("publisher_url", "");
            recipe.Title = jsonValue.GetNamedString("title", "");
            recipe.RecipeId = recipeId;

            return recipe;
        }
开发者ID:wcordeiro,项目名称:MobileApplications,代码行数:29,代码来源:Recipef2f.cs

示例8: IsInFastFood

        public async Task<bool> IsInFastFood(GeoCoordinate geo)
        {
            XmlDocument doc = new XmlDocument();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Accept", "text/xml");

                var squarreSize = 0.0002;
                var url = "http://api.openstreetmap.org/api/0.6/map?bbox=" +
                          (geo.Longitude - squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," +
                          (geo.Latitude - squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," +
                          (geo.Longitude + squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," +
                          (geo.Latitude + squarreSize).ToString("G", CultureInfo.InvariantCulture) + "&page=0";
                var uri = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(uri);
                if (response.IsSuccessStatusCode)
                {
                    var s = await response.Content.ReadAsStringAsync();
                    doc.LoadXml(s);
                    var listNodeTag = doc.SelectNodes("//tag[@k='amenity'][@v='fast_food']");
                   // var listNodeTag = doc.SelectNodes("//tag[@k='bus'][@v='bus']");
                    //var busFound = s.IndexOf("bus") > 0;
                    if (listNodeTag.Count > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
开发者ID:Noitacinrofilac,项目名称:Who-s-Hungry,代码行数:32,代码来源:FastFoodDetectorModel.cs

示例9: GetAsync

 private static async Task<string> GetAsync(string url)
 {
    var client = new HttpClient();
    var response = await client.GetAsync(new Uri(url));
    var result = await response.Content.ReadAsStringAsync();
    return result;
 }
开发者ID:mrange,项目名称:funbasic,代码行数:7,代码来源:Web.cs

示例10: SearchAsync

        public static async Task<List<FlickrImage>> SearchAsync(string tag)
        {
            var client = new HttpClient();

            const string apiKey = "8ebe03ac6480c2c43aeaf1183eec0eb9";
            const string baseUri = "https://api.flickr.com/services/rest/?method=flickr.photos.search&safe_search=1&per_page=25&content_type=1&media=photos&";

            var url = string.Format(
                    baseUri +
                    "api_key={0}&" +
                    "page={1}&" +
                    "tags={2}",
                    apiKey, 1, tag);

            var list = new List<FlickrImage>();

            using (var response = await client.GetAsync(new Uri(url, UriKind.Absolute)))
            {
                if (response.IsSuccessStatusCode)
                {
                    var contentxml = await response.Content.ReadAsStringAsync();
                    var xml = XElement.Parse(contentxml);
                    list = (from p in xml.DescendantsAndSelf("photo") select new FlickrImage(p)).ToList();
                }
            }
            return list;
        }
开发者ID:polatengin,项目名称:edinburgh,代码行数:27,代码来源:FlickrSearchHelper.cs

示例11: ThresholdExceeded_ThrowsException

        public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed)
        {
            await LoopbackServer.CreateServerAsync(async (server, url) =>
            {
                using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
                using (var client = new HttpClient(handler))
                {
                    Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

                    await LoopbackServer.AcceptSocketAsync(server, async (s, serverStream, reader, writer) =>
                    {
                        using (s) using (serverStream) using (reader) using (writer)
                        {
                            string line;
                            while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ;

                            byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders);
                            serverStream.Write(headerData, 0, headerData.Length);
                        }

                        if (shouldSucceed)
                        {
                            (await getAsync).Dispose();
                        }
                        else
                        {
                            await Assert.ThrowsAsync<HttpRequestException>(() => getAsync);
                        }
                        
                        return null;
                    });
                }
            });

        }
开发者ID:swaroop-sridhar,项目名称:corefx,代码行数:35,代码来源:HttpClientHandlerTest.MaxResponseHeadersLength.cs

示例12: HttpGets

        public static async Task<string> HttpGets(string uri)
        {


            if (Config.IsNetWork)
            {
                NotifyControl notify = new NotifyControl();
                notify.Text = "亲,努力加载中...";
              
                notify.Show();
                using (HttpClient httpClient = new HttpClient())
                {
                    try
                    {
                        HttpResponseMessage response = new HttpResponseMessage();
                        response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));
                        responseString = await response.Content.ReadAsStringAsync();
                        notify.Hide();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message.ToString());
                    }
                    
                  
                }
              
            }
            return responseString;
                
           

        }
开发者ID:x01673,项目名称:dreaming,代码行数:33,代码来源:HttpGet.cs

示例13: tokenIsValid

 public async Task<bool> tokenIsValid()
 {
     string access_token = null;
     if (tokenExists())
     {
         access_token = (string)ApplicationData.Current.LocalSettings.Values["Tokens"];
         string href = "https://api.teamsnap.com/v3/me";
         HttpClient httpClient = new HttpClient();
         httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);
         httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
         try
         {
             var httpResponseMessage = await httpClient.GetAsync(new Uri(href));
             Debug.WriteLine("http response status code : " + httpResponseMessage.StatusCode.ToString());
             if (httpResponseMessage.StatusCode.ToString().Equals("Ok"))
             {
                 return true;
             }
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Caught an Exception in tokenIsValid() " + ex);
             return false;
         }
     }
     Debug.WriteLine("tokenIsValid : Invalid token . returning false");
     return false;
 } 
开发者ID:agangal,项目名称:TeamSnapV3,代码行数:28,代码来源:Library_TokenAuth.cs

示例14: HttpGet

        public static async Task<string> HttpGet(string uri)
        {


            if (Config.IsNetWork)
            {
                NotifyControl notify = new NotifyControl();
                notify.Text = "亲,努力加载中...";
                notify.Show();
             
                var _filter = new HttpBaseProtocolFilter();
                using (HttpClient httpClient = new HttpClient(_filter))
                {

                    _filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    HttpResponseMessage response = new HttpResponseMessage();
                    response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));
                    responseString = await response.Content.ReadAsStringAsync();
                    notify.Hide();

                }

            }
            return responseString;



        }
开发者ID:x01673,项目名称:dreaming,代码行数:28,代码来源:HttpGetNoCache.cs

示例15: ProxyExplicitlyProvided_DefaultCredentials_Ignored

        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
开发者ID:naamunds,项目名称:corefx,代码行数:26,代码来源:HttpClientHandlerTest.DefaultProxyCredentials.cs


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