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


C# HttpClient.Dispose方法代码示例

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


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

示例1: 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

示例2: GetVideoStream

        public async static Task<UriShieldData> GetVideoStream(string url)
        {
            var client = new HttpClient();
            string message;

            try
            {
                if (url.EndsWith("Manifest"))
                {
                    url += "?type=json&protection=url";
                }
                else
                {
                    url += "&type=json&protection=url";
                }
                var response = await client.GetStringAsync(new Uri(url));
                UriShieldData data = new UriShieldData();
                data.Subtitles = false;
                data.Url = JsonConvert.DeserializeObject<string>(response);

                client.Dispose();

                return data;
            }
            catch (Exception hrex)
            {
                message = hrex.Message;
                client.Dispose();
            }

            MessageBox.Show(string.Format(ResourceHelper.GetString("WebErrorMessage"), message));
            return new UriShieldData();
        }
开发者ID:se-bastiaan,项目名称:TVNL-WindowsPhone,代码行数:33,代码来源:StreamService.cs

示例3: SendRequest

        public async Task<bool> SendRequest()
        {
            try
            {
                var config = new ConfigurationViewModel();
                var uri = new Uri(config.Uri + _path);

                var filter = new HttpBaseProtocolFilter();
                if (config.IsSelfSigned == true)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                }

                var httpClient = new HttpClient(filter);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain"));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString()));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString()));

                var reponse = await httpClient.GetAsync(uri);
                httpClient.Dispose();
                return reponse.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:phabrys,项目名称:Domojee,代码行数:29,代码来源:HttpRpcClient.cs

示例4: GetPlaylistAsync

        public static async Task<Album> GetPlaylistAsync(string link)
        {
            try
            {
                HttpClient hc = new HttpClient();

                hc.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 45.0.2454.101 Safari / 537.36"));
                string htmlPage = await hc.GetStringAsync(new Uri(link));
                string xmlLink = Regex.Split(htmlPage, "amp;file=")[1].Split('\"')[0];
                XDocument xdoc = XDocument.Parse(await hc.GetStringAsync(new Uri(xmlLink)));
                hc.Dispose();

                //Parse xml
                var trackList = from t in xdoc.Descendants("track")
                                select new Track()
                                {
                                    Title = t.Element("title").Value,
                                    Artist = t.Element("creator").Value,
                                    Location = t.Element("location").Value,
                                    Info = t.Element("info").Value,
                                    ArtistLink = t.Element("newtab").Value,
                                    Image = t.Element("bgimage").Value
                                };

                Album album = new Album();
                album.Link = link;
                album.TrackList = trackList.ToList();
                return album;
            }
            catch (Exception)
            {
                return null;
            }

        }
开发者ID:thongbkvn,项目名称:NCT,代码行数:35,代码来源:NhacCuaTui.cs

示例5: DoLogin

        /// <summary>
        /// 约定成功登陆返回0,不成功返回错误代码,未知返回-1
        /// </summary>
        /// <returns></returns>
        public async Task<int> DoLogin()
        {
            var httpClient = new HttpClient();
            var requestUrl = "https://net.zju.edu.cn/cgi-bin/srun_portal";
            var formcontent = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("action","login"),
                new KeyValuePair<string, string>("username",_mAccount.Username),
                new KeyValuePair<string, string>("password",_mAccount.Password),
                new KeyValuePair<string, string>("ac_id","3"),
                new KeyValuePair<string, string>("type","1"),
                new KeyValuePair<string, string>("wbaredirect",@"http://www.qsc.zju.edu.cn/"),
                new KeyValuePair<string, string>("mac","undefined"),
                new KeyValuePair<string, string>("user_ip",""),
                new KeyValuePair<string, string>("is_ldap","1"),
                new KeyValuePair<string, string>("local_auth","1"),
            });
            var response = await httpClient.PostAsync(new Uri(requestUrl), formcontent);
            if (response.Content != null)
            {
                string textMessage = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(textMessage);
            }

            httpClient.Dispose();

            return -1;
        }
开发者ID:yzyDavid,项目名称:ZJUWLANManager,代码行数:32,代码来源:Login.cs

示例6: Authenticate

        public static async Task<string> Authenticate()
        {
            var startURI = new Uri(START_URL);
            var endURI = new Uri(END_URL);
            string result;

            var webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);

            switch (webAuthResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = webAuthResult.ResponseData.ToString();
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = webAuthResult.ResponseData.ToString();
                    throw new Exception(result);
                default:
                    throw new Exception("Error :(");
            }
            var resultURI = new Uri(result);
            var query = resultURI.ParseQueryString();
            var code = query["code"];
            var tokenURL = "https://api.slack.com/api/oauth.access?code="
                + Uri.EscapeUriString(code)
                + "&client_id=" + Uri.EscapeUriString(CLIENT_ID)
                + "&client_secret=" + Uri.EscapeUriString(CLIENT_SECRET);
            var tokenURI = new Uri(tokenURL);
            var httpClient = new HttpClient();
            string tokenResponse;
            try
            {
                tokenResponse = await httpClient.GetStringAsync(tokenURI);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                httpClient.Dispose();
            }
            JsonObject tokenObject;
            if (!JsonObject.TryParse(tokenResponse, out tokenObject))
            {
                throw new Exception("Couldn't parse HTTP response. Try again later.");
            }
            if (!tokenObject.GetNamedBoolean("ok"))
            {
                throw new Exception("You are not authorized to access this team.");
            }
            return tokenObject.GetNamedString("access_token");
        }
开发者ID:kureuil,项目名称:Taper,代码行数:52,代码来源:LoginProvider.cs

示例7: CreateHttpClient

        internal static void CreateHttpClient(ref HttpClient httpClient)
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
            }
            //添加过滤器
            IHttpFilter filter = new HttpBaseProtocolFilter();
            filter = new PlugInFilter(filter);
            httpClient = new HttpClient(filter);

            //添加User-Agent
            httpClient.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("mySample", "v1"));
        }
开发者ID:cnlinxi,项目名称:WebApiDemo,代码行数:14,代码来源:HttpHelper.cs

示例8: PostWebServiceDataAsync

        private async Task PostWebServiceDataAsync(string mediaId)
        {
            try
            {
                Random random = new Random();
                int r = random.Next();
                string requestUrl = "http://replatform.cloudapp.net:8000/userAction?uuid={0}&type={1}&media_id={2}&from={3}&to={4}&r={5}";
                string userid = App.gDeviceName;
                requestUrl = String.Format(requestUrl, userid, App.gDeviceType, mediaId, App.NavigationRoadmap.GetFrom(), App.NavigationRoadmap.GetTo(), r);

                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                filter.AutomaticDecompression = true;
                HttpClient httpClient = new HttpClient(filter);
                CancellationTokenSource cts = new CancellationTokenSource();

                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;

                Uri resourceUri;
                if (!Uri.TryCreate(requestUrl.Trim(), UriKind.Absolute, out resourceUri))
                {
                    return;
                }

                HttpResponseMessage response = await httpClient.GetAsync(resourceUri).AsTask(cts.Token);
                string jsonText = await Helpers.GetResultAsync(response, cts.Token);

                GetPostUserActionResult(jsonText);

                if (filter != null)
                {
                    filter.Dispose();
                    filter = null;
                }

                if (httpClient != null)
                {
                    httpClient.Dispose();
                    httpClient = null;
                }

                if (cts != null)
                {
                    cts.Dispose();
                    cts = null;
                }
            }
            catch (Exception) { }
        }
开发者ID:RaulVan,项目名称:Recommender,代码行数:49,代码来源:ReUserActionDataSource.cs

示例9: GetTaiwanUVData

        //透過HttpClient 去取得紫外線Open Data 
        public async Task<List<TaiwanCityUV>> GetTaiwanUVData()
        {

                List<TaiwanCityUV> taiwanUVData = new List<TaiwanCityUV>();

                string content = "";

                HttpClient httpClient = new HttpClient();
                try
                {
                    content = await httpClient.GetStringAsync(new Uri(TaiwanUVOpenDataUrl));

                    RawContent = content;
                    JsonArray jArray = JsonArray.Parse(content);
                    IJsonValue outValue;

                    string testContent = "";
                    foreach (var item in jArray)
                    {
                        JsonObject obj = item.GetObject();
                        // Assume there is a “backgroundImage” column coming back
                        if (obj.TryGetValue("SiteName", out outValue))
                        {
                            testContent += outValue.GetString() + " ";
                        }


                    }
                    RawContent = testContent;
                    RawContent = "There are " + taiwanUVData.Count + " " + RawContent;

                    taiwanUVData=DeserializeTaiwanUVJason(content);                  
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message+ " "+ ex.StackTrace);

                    var telemetry = new TelemetryClient();
                    telemetry.TrackException(ex);
                            
            }

            // Once your app is done using the HttpClient object call dispose to 

            httpClient.Dispose();
            return taiwanUVData;

        }
开发者ID:liqinghuang,项目名称:TaiwanUV,代码行数:49,代码来源:TaiwanUVOpenDataService.cs

示例10: CreateHttpClient

        internal static void CreateHttpClient(ref HttpClient httpClient)
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
            }

            // HttpClient functionality can be extended by plugging multiple filters together and providing
            // HttpClient with the configured filter pipeline.
            IHttpFilter filter = new HttpBaseProtocolFilter();
            filter = new PlugInFilter(filter); // Adds a custom header to every request and response message.
            httpClient = new HttpClient(filter);

            // The following line sets a "User-Agent" request header as a default header on the HttpClient instance.
            // Default headers will be sent with every request sent from this HttpClient instance.
            httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("Sample", "v8"));
        }
开发者ID:trilok567,项目名称:Windows-Phone,代码行数:17,代码来源:Helpers.cs

示例11: GetTopTrackListAsync

        public static async Task<Album> GetTopTrackListAsync(string link)
        {
            Album album = new Album();
            album.Link = link;
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.UserAgent.Add(new Windows.Web.Http.Headers.HttpProductInfoHeaderValue("Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 45.0.2454.101 Safari / 537.36"));
            string response = await client.GetStringAsync(new Uri(link));
            client.Dispose();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(response);

            //Lay album title tu header
            album.Title = doc.DocumentNode.ChildNodes["html"].ChildNodes["head"].ChildNodes["title"].InnerText;
            //Chon ra the ul chua danh sach bai hat
            var ulTags = from ul in doc.DocumentNode.Descendants("ul").Where(x => x.Attributes["class"].Value == "list_show_chart")
                         select ul;
            var ulTag = ulTags.First();

            //Moi node la 1 the li
            foreach (HtmlNode node in ulTag.ChildNodes)
            {
                //Loai bo the #text
                if (node.Name == "li")
                {
                    try
                    {
                        HtmlNode trackInfoNode = node.ChildNodes[5];
                        Track track = new Track();
                        track.Title = trackInfoNode.ChildNodes[3].ChildNodes[0].InnerText;
                        track.Info = trackInfoNode.ChildNodes[3].ChildNodes[0].Attributes["href"].Value;
                        track.Image = trackInfoNode.ChildNodes[1].ChildNodes["img"].Attributes["src"].Value;
                        track.Artist = trackInfoNode.ChildNodes[5].ChildNodes[1].InnerText;
                        track.ArtistLink = trackInfoNode.ChildNodes[5].ChildNodes[1].Attributes["href"].Value;
                        album.TrackList.Add(track);
                    }

                    catch (Exception)
                    { }

                }
            }

            return album;
        }
开发者ID:thongbkvn,项目名称:NCT,代码行数:44,代码来源:NhacCuaTui.cs

示例12: GetJson

        public int GetJson(out string jsonFile)
        {
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource(3000);
                HttpClient httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(addressapi));
                HttpResponseMessage response = httpClient.SendRequestAsync(request).AsTask().Result;

                jsonFile = response.Content.ToString();
                httpClient.Dispose();
                return 0;
            }
            catch (Exception ex)
            {
                jsonFile = ex.Message;
                return (int)ex.HResult;
            }
        }
开发者ID:rftemer,项目名称:WindowsPhone,代码行数:19,代码来源:RestAPI.cs

示例13: FetchData

 public static async Task<JsonObject> FetchData(string token)
 {
     var httpClient = new HttpClient();
     var teamInfoURL = BASE_URL + Uri.EscapeUriString(token);
     var teamInfoURI = new Uri(teamInfoURL);
     var teamInfoStr = await httpClient.GetStringAsync(teamInfoURI);
     httpClient.Dispose();
     JsonObject teamInfoObject;
     if (!JsonObject.TryParse(teamInfoStr, out teamInfoObject))
     {
         // Error :(
         throw new Exception("Couldn't parse JSON object.");
     }
     if (!teamInfoObject.GetNamedBoolean("ok"))
     {
         // Error :(
         throw new Exception("Request was not successful.");
     }
     return teamInfoObject.GetNamedObject("team");
 }
开发者ID:kureuil,项目名称:Taper,代码行数:20,代码来源:SlackTeam.cs

示例14: sendGetRequest

        //public static string preServiceURI = "http://52.11.206.209/RESTFul/v1/";
        //public static string preServiceURI = "http://54.68.126.75/RESTFul/v1/";
        

        public static async Task<string> sendGetRequest(string methodName)
        {
            Random r = new Random();
            int x = r.Next(-1000000, 1000000);
            double y = r.NextDouble();
            double randomNumber = x + y;
            string ServiceURI = preServiceURI + methodName + "?xxx=" + randomNumber.ToString();
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.RequestUri = new Uri(ServiceURI);
            request.Headers.Authorization = Windows.Web.Http.Headers.HttpCredentialsHeaderValue.Parse(Global.GlobalData.APIkey);
            //request.Headers.Authorization = Windows.Web.Http.Headers.HttpCredentialsHeaderValue.Parse("ce1fb637b7eee845c73b207d931bbc10");
            HttpResponseMessage response = await httpClient.SendRequestAsync(request);
            string returnString = await response.Content.ReadAsStringAsync();
            response.Dispose();
            httpClient.Dispose();
            request.Dispose();        
            return returnString;
            
        }
开发者ID:kleitz,项目名称:WPApp,代码行数:25,代码来源:RequestToServer.cs

示例15: FetchChannels

 public async Task FetchChannels()
 {
     var httpClient = new HttpClient();
     var channelsURL = CHANNELS_URL + Uri.EscapeUriString(Token);
     var channelsURI = new Uri(channelsURL);
     var channelsStr = await httpClient.GetStringAsync(channelsURI);
     httpClient.Dispose();
     JsonObject channelsObject;
     if (!JsonObject.TryParse(channelsStr, out channelsObject))
     {
         throw new Exception("Couldn't parse JSON object.");
     }
     if (!channelsObject.GetNamedBoolean("ok"))
     {
         throw new Exception("Request was not successful.");
     }
     var channelsArray = channelsObject.GetNamedArray("channels");
     Channels = new ObservableCollection<SlackChannel>();
     foreach (var channel in channelsArray)
     {
         Channels.Add(new SlackChannel(channel.GetObject()));
     }
 }
开发者ID:kureuil,项目名称:Taper,代码行数:23,代码来源:SlackTeam.cs


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