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


C# System.Net.Http.HttpClient.GetAsync方法代码示例

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


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

示例1: Foo

        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();
        }
开发者ID:kiewic,项目名称:Projects,代码行数:30,代码来源:Program.cs

示例2: OnNavigatedTo

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            date.Text = DateTime.Today.ToString("d.M.yyyy");
            System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response = await hc.GetAsync("http://api.teknolog.fi/taffa/sv/today/");
            response.EnsureSuccessStatusCode();
            menu.Text = await response.Content.ReadAsStringAsync();


            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text05);

            XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
            tileTextAttributes[0].InnerText = menu.Text;


            XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text03);
            XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
            squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(menu.Text));
            IXmlNode node = tileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            TileNotification tileNotification = new TileNotification(tileXml);

            tileNotification.ExpirationTime = DateTime.Now.Date.AddDays(1);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);



        }
开发者ID:noletreni,项目名称:dagsen-windows,代码行数:30,代码来源:MainPage.xaml.cs

示例3: GetAsync

        protected async Task<System.Net.Http.HttpResponseMessage> GetAsync(string url)
#endif
        {
            if (url == null) throw new ArgumentNullException(nameof(url));

            try
            {
                var uri = new Uri(url);

#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
                using (var client = new System.Net.Http.HttpClient())
#elif WINDOWS_UAP
                using (var client = new System.Net.Http.HttpClient())
#endif
                {
#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
                    // Setting timeout for httpclient on portable architecture. 
                    // UAP supports timeout configuration via System.Threading.Task
                    if (ProxyConfiguration.Timeout.HasValue)
                    {
                        client.Timeout = ProxyConfiguration.Timeout.Value;
                    }
#endif

                    var response = await client.GetAsync(uri, System.Net.Http.HttpCompletionOption.ResponseContentRead);
                    if (!response.IsSuccessStatusCode) throw new TheTvDbBadResponseException(response.StatusCode);

                    return response;
                }
            }
            catch (Exception e)
            {
                throw new TheTvDbServerNotAvailableException(inner: e);
            }
        }
开发者ID:StuartMeeks,项目名称:TheTVDBSharp,代码行数:35,代码来源:TheTvDbProxyBase.cs

示例4: GetResponse

 // function for map sdk
 private async Task<BingMapHelper.Response> GetResponse(Uri uri)
 {
     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
     var response = await client.GetAsync(uri);
     using (var stream = await response.Content.ReadAsStreamAsync())
     {
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BingMapHelper.Response));
         return ser.ReadObject(stream) as BingMapHelper.Response;
     }
 }
开发者ID:Voropash,项目名称:CheaTaxiWin10,代码行数:11,代码来源:DrowPath.cs

示例5: GetQueriesAsync

		public async Task<RelatedTopic[]> GetQueriesAsync () {
			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://api.duckduckgo.com/");

			var response = await client.GetAsync("?q=tijuana&format=json&pretty=1");
			var queriesJson = response.Content.ReadAsStringAsync().Result;
			var rootObject = JsonConvert.DeserializeObject<RootObject>(queriesJson);

			return rootObject.RelatedTopics;
		}
开发者ID:jonathanzuniga,项目名称:JsonToListView,代码行数:11,代码来源:RestService.cs

示例6: CallService

 private async Task<RootObject> CallService(Uri uri)
 {
     string _JsonString = string.Empty;
     // fetch from rest service             
     var _HttpClient = new System.Net.Http.HttpClient();
     var _HttpResponse = await _HttpClient.GetAsync(uri.ToString());
     _JsonString = await _HttpResponse.Content.ReadAsStringAsync();
     // deserialize json to objects        
     var _JsonBytes = Encoding.Unicode.GetBytes(_JsonString);
     using (MemoryStream _MemoryStream = new MemoryStream(_JsonBytes))
     { var _JsonSerializer = new DataContractJsonSerializer(typeof(RootObject)); var _Result = (RootObject)_JsonSerializer.ReadObject(_MemoryStream); return _Result; }
 }
开发者ID:broomandan,项目名称:Win8CoffeeFinder,代码行数:12,代码来源:ResultsModel.cs

示例7: Request

        public static object Request(object request, Type responseType=null, bool post=false)
        {
            /** determine the api method to call */
            string method = Mozu.getMethod(request);
            if (responseType == null) responseType = request.GetType();

            /** make sure we have a valid authentication ticket */
            if (_auth == null && request.GetType() != typeof(AuthenticationContract)) Mozu.authenticate();

            string url = string.Format("{0}{1}", _apiUrl, method);
            Type t = request.GetType();
            bool get = false;
            if (! post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com";
                get = true;
            }
            else if (post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com/api/platform";
            }
            //HTTP http = new HTTP();
            Console.WriteLine("Calling Mozu API: " + url);
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient { BaseAddress = new Uri(url) };
            //if (request.GetType() != typeof(AuthenticationContract)) http.AddHeader("x-vol-app-claims", _auth.Ticket.AccessToken);
            if (t != typeof(AuthenticationContract)) {
                client.DefaultRequestHeaders.Add("x-vol-app-claims", _auth.Ticket.AccessToken);
                client.DefaultRequestHeaders.Add("x-vol-tenant", "7949");//the sandbox number
                if (t == typeof(Product)) {
                    client.DefaultRequestHeaders.Add("x-vol-master-catalog", "2");
                }
                //client.DefaultRequestHeaders.Add("x-vol-catalog", "1");
                //client.DefaultRequestHeaders.Add("x-vol-version", "1.9.14232.3");
            }

            string json = JSON.Serialize(request);

            //string response = http.POSTRaw(url, json, "application/json");

            string response = null;
            if (get) {
                method = "/api" + method;
                if (t == typeof(Product)) method += "?startindex=0&pagesize=200";
                var r = client.GetAsync(method).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }
            else {
                var r = client.PostAsync("/api" + method, new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }

            object o = JSON.Deserialize(response, responseType);
            return o;
        }
开发者ID:warwickit,项目名称:MozuFreestyle,代码行数:52,代码来源:Mozu.cs

示例8: GetResponseContentAsync

 private async Task<string> GetResponseContentAsync(string url)
 {
     var httpClient = new System.Net.Http.HttpClient();
     var response = await httpClient.GetAsync(url);
     if (response.StatusCode == System.Net.HttpStatusCode.OK)
     {
         return await response.Content.ReadAsStringAsync();
     }
     else
     {
         return "error";
     }
 }
开发者ID:org-itbiz,项目名称:DocumentExT,代码行数:13,代码来源:HomeController.cs

示例9: GetCurrentVersion

 public async void GetCurrentVersion(Action<int> callback)
 {
     try
     {
         var client = new System.Net.Http.HttpClient();
         var response = await client.GetAsync(new Uri(_baseUrl + "/Version"));
         callback(int.Parse(response.Content.ReadAsString()));
     }
     catch (Exception)
     {
         callback(-1);
     }
 }
开发者ID:bendewey,项目名称:NycCodeCamp6,代码行数:13,代码来源:CodeCampDataClient.cs

示例10: GetDataFromUri

 public static async Task<Byte[]> GetDataFromUri(Uri uri)
 {
     using (System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient())
     {
         Client.BaseAddress = uri;
         var resultContext = await Client.GetAsync(uri);
         if (resultContext != null)
         {
             return await resultContext.Content.ReadAsByteArrayAsync();
         }
     }
     return null;
 }
开发者ID:peacecwz,项目名称:Omubumu,代码行数:13,代码来源:FileHelper.cs

示例11: Get

        // GET api/ManageUser
        public async Task<string> Get()
        {
            Web.Models.ConfigModel config = new Web.Models.ConfigModel();
            string retVal = config.DefaultUserId;

            // Get the credentials for the logged-in user.
            var fbCredentials = await this.User.GetAppServiceIdentityAsync<FacebookCredentials>(this.Request);

            if (null != fbCredentials && fbCredentials.Claims.Count > 0)
            {
                // Create a query string with the Facebook access token.
                var fbRequestUrl = "https://graph.facebook.com/v2.5/me?fields=email%2Cfirst_name%2Clast_name&access_token="
                    + fbCredentials.AccessToken;

                // Create an HttpClient request.
                var client = new System.Net.Http.HttpClient();

                // Request the current user info from Facebook.
                var resp = await client.GetAsync(fbRequestUrl);
                resp.EnsureSuccessStatusCode();

                // Do something here with the Facebook user information.
                var fbInfo = await resp.Content.ReadAsStringAsync();

                JObject fbObject = JObject.Parse(fbInfo);
                var emailToken = fbObject.GetValue("email");

                if (null != emailToken)
                {
                    string email = emailToken.ToString();
                    retVal = CheckAddEmailToDB(email);
                }
                else
                {
                    return retVal;
                }

                return retVal;
            }

            var aadCredentials = await this.User.GetAppServiceIdentityAsync<AzureActiveDirectoryCredentials>(this.Request);
            if (null != aadCredentials && aadCredentials.Claims.Count > 0)
            {
                string email = aadCredentials.UserId;

                retVal = CheckAddEmailToDB(email);
            }

            return retVal;
        }
开发者ID:cephalin,项目名称:ContosoMoments,代码行数:51,代码来源:ManageUserController.cs

示例12: getHttpWebRequest

        public static async Task<string> getHttpWebRequest(string api, List<KeyValuePair<String, String>> paramList = null, int PostORGet = 0, bool fulluri = false)
        {
            string content = "";
            return await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        string uri;
                        if (!fulluri)
                            uri = "http://hongyan.cqupt.edu.cn/" + api;
                        else
                            uri = api;
                        httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
                        httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;
                        if (PostORGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                        }
                        else
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(uri)).Result;
                        }
                        if (response.StatusCode == HttpStatusCode.OK)
                            content = response.Content.ReadAsStringAsync().Result;
                        //else if (response.StatusCode == HttpStatusCode.NotFound)
                        //    Utils.Message("Oh...服务器又跪了,给我们点时间修好它");

                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                else
                {
                }
                //if (content.IndexOf("{") != 0)
                //    return "";
                //else
                return content;

            });
        }
开发者ID:RedrockMobile,项目名称:CyxbsMobile_Win,代码行数:50,代码来源:NetWork.cs

示例13: GetDocument

        public async Task<string> GetDocument(string key, int imageId)
        {
            var client = new System.Net.Http.HttpClient
            {
                BaseAddress = new Uri(Constants.SERVICE_URL)
            };
            client.DefaultRequestHeaders.Add("X-Client-Identifier", DeviceDetail.DeviceIdentifierInfo);
            client.DefaultRequestHeaders.Add("application_key", DeviceDetail.UserKey);
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + CommonHelper.GetTokenInfo());
            Debug.WriteLine(Constants.FIRST_DOCUMENT_URL + "Get?folder=" + key + "&page=" + imageId);
			var response = client.GetAsync(Constants.FIRST_DOCUMENT_URL + "/Get?folder=" + key + "&page=" + imageId).Result;
            string content = await response.Content.ReadAsStringAsync();
			
            return content;
        }
开发者ID:Aranjedeath,项目名称:SpecimenCode,代码行数:15,代码来源:DocumentDetailServiceAgent.cs

示例14: GetEarthquakesAsync

		public async Task<Earthquake[]> GetEarthquakesAsync () {

			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://api.geonames.org/");

			var response = await client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt&maxRows=20");

			var earthquakesJson = response.Content.ReadAsStringAsync().Result;

			var rootobject = JsonConvert.DeserializeObject<RootobjectE>(earthquakesJson);

			return rootobject.earthquakes;

		}
开发者ID:Randy3W,项目名称:xamarin-forms-samples,代码行数:15,代码来源:GeoNamesWebService.cs

示例15: GetXml

 public async void GetXml(Action<string> callback)
 {
     string xml = null;
     try
     {
         var client = new System.Net.Http.HttpClient() { MaxResponseContentBufferSize = Int32.MaxValue };
         var response = await client.GetAsync(new Uri(_baseUrl + "/Xml"));
         xml = response.Content.ReadAsString();
     }
     catch (Exception ex) 
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     callback(xml);
 }
开发者ID:bendewey,项目名称:NycCodeCamp6,代码行数:15,代码来源:CodeCampDataClient.cs


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