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


C# HttpClient.Dispose方法代码示例

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


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

示例1: Execute

        public override bool Execute()
        {
            HttpClient client = null;
            try {
                var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
                var mediaType = new MediaTypeHeaderValue("application/json");
                var jsonSerializerSettings = new JsonSerializerSettings();
                var requestMessage = new HttpRequestMessage<string>(
                    this.PostContent,
                    mediaType,
                    new MediaTypeFormatter[] { jsonFormatter });

                client = new HttpClient();
                HttpResponseMessage response = null;
                System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => {
                    response = respMessage.Result;
                });

                System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask });

                response.EnsureSuccessStatusCode();

                return true;
            }
            catch (Exception ex) {
                string message = "Unable to post the message.";
                throw new LoggerException(message,ex);
            }
            finally {
                if (client != null) {
                    client.Dispose();
                    client = null;
                }
            }
        }
开发者ID:JustJenFelice,项目名称:sayed-samples,代码行数:35,代码来源:JsonHttpPost.cs

示例2: PostDashEvent

        private static void PostDashEvent(EthernetPacket packet)
        {
            if (((ARPPacket)packet.PayloadPacket).SenderProtocolAddress.ToString() != "0.0.0.0")
                return;

            var macAddress = packet.SourceHwAddress.ToString();
            var button = ConfigurationManager.AppSettings.AllKeys.SingleOrDefault(m => m.Contains(macAddress));

            if (button == null)
                return;

            var client = new HttpClient();
            var values = new Dictionary<string, string>
                {
                    {"Event", ConfigurationManager.AppSettings[button] },
                    {"MacAddress", macAddress },
                    {"CreatedOn", DateTime.Now.ToString() }
                };

            var data = new FormUrlEncodedContent(values);
            client.PostAsync("http://localhost:56719/your/api/url/here", data).ContinueWith(task =>
            {
                client.Dispose();
            });
        }
开发者ID:upnxt,项目名称:upnxt-dash-arp-sniffer,代码行数:25,代码来源:DashEventHandler.cs

示例3: UpdateProduct

 static bool UpdateProduct(ProductViewModel newProduct)
 {
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(baseURL);
     var response = client.PutAsJsonAsync("api/Products/", newProduct).Result;
     client.Dispose();
     return response.Content.ReadAsAsync<bool>().Result;
 }
开发者ID:SreekanthSPillai,项目名称:refFramework,代码行数:8,代码来源:ProductAPI.cs

示例4: CreateHttpClient

        public static HttpClient CreateHttpClient()
        {
            var baseAddress = new Uri("http://localhost:8080");

            var config = new HttpSelfHostConfiguration(baseAddress);

            // ?
            Setup.Configure(config);

            var server = new HttpSelfHostServer(config);

            var client = new HttpClient(server); // <--- MAGIC!

            try
            {
                client.BaseAddress = baseAddress;
                return client;

            }
            catch
            {
                client.Dispose();
                throw;
            }
        }
开发者ID:JeffryGonzalez,项目名称:HRSolution,代码行数:25,代码来源:Helpers.cs

示例5: LoginUser

        public async Task<string> LoginUser(string username, string password)
        {
            string tokenUrl = string.Format("{0}Token", _configuration.BaseAddress);
            var client = new HttpClient();

            // using postBody I got invalid grant type
            // using postData I got 200 OK! :-) TODO I wonder why? couldn't find a hex dump in fiddler composer
            //string postBody =
            //    String.Format("username={0}&amp;password={1}&amp;grant_type=password",
            //        WebUtility.HtmlEncode(username), WebUtility.HtmlEncode(password));
            //Logger.Log(this, postBody);
            // HttpContent content = new StringContent(postBody);

            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("username", username));
            postData.Add(new KeyValuePair<string, string>("password", password));
            postData.Add(new KeyValuePair<string, string>("grant_type", "password"));

            Logger.Log(this, "postData", postData.ToString());
            HttpContent content = new FormUrlEncodedContent(postData);
            HttpResponseMessage response = await client.PostAsync(tokenUrl, content);
            Logger.Log(this, "response", response.Content.ToString());
            string result = await response.Content.ReadAsStringAsync();
            Logger.Log(this, "result", result);
            TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(result);
            AccessToken = tokenResponse.AccessToken;
            Logger.Log(this, "AccessToken", AccessToken);
            client.Dispose();
            await GetValues();
            return AccessToken;
        }
开发者ID:jhalbrecht,项目名称:IdentityDemo,代码行数:31,代码来源:IdentityService.cs

示例6: DownloadStringAsync

 public async static Task<string> DownloadStringAsync(string url)
 {
     var tcs = new CancellationTokenSource();
     var client = new HttpClient();
     lock (lck)
     {
         cancelTokens.Add(tcs);
     }
     string res = null;
     try
     {
         var x = await client.GetAsync(url, tcs.Token);
         res = await x.Content.ReadAsStringAsync();
     }
     catch (Exception e)
     {
        
     }
     finally
     {
         client.Dispose();
         lock (lck)
         {
             cancelTokens.Remove(tcs);
         }
         tcs.Dispose();
     }
     return res;
 }
开发者ID:3ricguo,项目名称:xiami_downloader,代码行数:29,代码来源:NetAccess.cs

示例7: HttpWebRequestGet

        //public static async Task<string> PostCreateAsync(string data, string uri, string contenType)
        //{
        //    HttpClient client = new HttpClient();
        //    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

        //    request.Content = new StringContent(data, Encoding.UTF8, contenType);
        //    HttpResponseMessage response = await client.SendAsync(request);
        //    string responseString = await response.Content.ReadAsStringAsync();
        //    return responseString;
        //}

        //public static async Task<string> PostBatchCreateAsync(string data, string uri, string contenType)
        //{
        //    HttpClient client = new HttpClient();
        //    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

        //    request.Content = new StringContent(data, Encoding.UTF8, contenType);
        //    HttpResponseMessage response = await client.SendAsync(request);
        //    string responseString = await response.Content.ReadAsStringAsync();
        //    return responseString;
        //}

        ////public async Task<string> Post(string data, Uri uri)
        ////{
        ////    HttpClient client = new HttpClient();
        ////    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
        ////    request.Content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
        ////    HttpResponseMessage response = await client.SendAsync(request);
        ////    string responseString = await response.Content.ReadAsStringAsync();
        ////    return responseString;
        ////}

        //public static async Task<string> Get(string data, string uri)
        //{
        //    HttpClient client = new HttpClient();
        //    HttpResponseMessage response = await client.GetAsync(string.Format("{0}{1}", uri, data));
        //    string responseString = await response.Content.ReadAsStringAsync();
        //    //TODO:判断返回的status,

        //    return responseString;
        //}
        //public static string ToJson(object jsonObject)
        //{
        //    var result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
        //    return result;
        //} 

       

       public static async Task<String> HttpWebRequestGet(string address)
       {
           try
           {
               #if  NETFX_CORE
            
                HttpClient client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(address);
                response.Headers.Add("User-Agent", "AMap SDK Windows8 CloudMap Beta1.1.0");
                client.Dispose();
                return await response.Content.ReadAsStringAsync();
            
#elif WINDOWS_PHONE             
               HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
               request.Method = "GET";
               

               HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
               using (var sr = new StreamReader(response.GetResponseStream()))
               {
                   return sr.ReadToEnd();
               }

#endif
           }
           catch (Exception ex)
           {

               throw ex;
           }
       }
开发者ID:RaulVan,项目名称:YunTuforWPSDK,代码行数:80,代码来源:HttpConnect.cs

示例8: CreateTag

        public string CreateTag(Tag model, UserData userData)
        {
            try
            {
                client = new HttpClient();
                var postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string>("name", model.name));

                HttpContent content = new FormUrlEncodedContent(postData);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                content.Headers.Add("Timestamp", userData.Timestamp.ToString());
                content.Headers.Add("Digest", userData.AuthenticationHash);
                content.Headers.Add("Public-Key", userData.PublicKey);

                client.PostAsync("http://localhost:3000/tag", content)
                    .ContinueWith(postTask =>
                    {
                        postTask.Result.EnsureSuccessStatusCode();
                        var result = postTask.Result.Content.ReadAsStringAsync();
                        client.Dispose();
                        return result;

                    });

            }
            catch (Exception ex)
            {
                throw ex;

            }
            return null;
        }
开发者ID:robertzur,项目名称:ContactBookWebClient,代码行数:32,代码来源:TagEndpoint.cs

示例9: DeleteGroup

        public string DeleteGroup(string id, UserData userData)
        {
            try
            {
                client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Timestamp", userData.Timestamp.ToString());
                client.DefaultRequestHeaders.Add("Digest", userData.AuthenticationHash);
                client.DefaultRequestHeaders.Add("Public-Key", userData.PublicKey);

                client.DeleteAsync("http://localhost:3000/contact/" + id)
                    .ContinueWith(deleteTask =>
                    {
                        deleteTask.Result.EnsureSuccessStatusCode();
                        var result = deleteTask.Result.Content.ReadAsStringAsync();
                        client.Dispose();
                        return result;

                    });

            }
            catch (Exception ex)
            {
                throw ex;

            }
            return null;
        }
开发者ID:robertzur,项目名称:ContactBookWebClient,代码行数:29,代码来源:GroupEndpoint.cs

示例10: GetFacebookUser

    } // End of the GetFacebookAccessToken method

    /// <summary>
    /// Get a facebook user as a dictionary
    /// </summary>
    /// <param name="domain">A reference to the current domain</param>
    /// <param name="access_token">The access token</param>
    /// <returns>A dictionary with user information</returns>
    public async static Task<Dictionary<string, object>> GetFacebookUser(Domain domain, string access_token)
    {
        // Create a dictionary to return
        Dictionary<string, object> facebookUser = new Dictionary<string, object>();

        // Create the new url
        string url = "https://graph.facebook.com/me?access_token=" + access_token;

        // Create a http client
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // Get the facebook user
        HttpResponseMessage response = await client.GetAsync(url);

        // Make sure that the response is successful
        if (response.IsSuccessStatusCode)
        {
            facebookUser = await response.Content.ReadAsAsync<Dictionary<string, object>>();
        }

        // Dispose of the client
        client.Dispose();

        // Return the facebook user
        return facebookUser;

    } // End of the GetFacebookUser method
开发者ID:hunii,项目名称:a-blogsite,代码行数:37,代码来源:AnnytabExternalLogin.cs

示例11: ExecuteQuery

        public async Task<List<GeocodeResult>> ExecuteQuery(string query)
        {
            query = Uri.EscapeUriString(query);

            string URL =
                String.Format(
                    "http://open.mapquestapi.com/nominatim/v1/search?format=xml&q={0}&addressdetails=0&limit={1}&countrycodes=at&exclude_place_ids=613609",
                    query,
                    15);    // max. results to return, possibly make this configurable

            string response = "";
            using (var client = new HttpClient())
            {
                response = await client.GetStringAsync(URL);
                client.Dispose();
            }

            var searchresults = XElement.Parse(response);
            var mapped = searchresults.Elements("place")
                .Select(e => new GeocodeResult()
                {
                    Name = (string)e.Attribute("display_name"),
                    Longitude = MappingHelpers.ConvertDouble((string)e.Attribute("lon")),
                    Latitude = MappingHelpers.ConvertDouble((string)e.Attribute("lat")),
                })
                .ToList();

            return mapped;
        }
开发者ID:christophwille,项目名称:Sprudelsuche,代码行数:29,代码来源:NominatimProxy.cs

示例12: LoadVehicleDetails

        public async Task LoadVehicleDetails()
        {
            listOfNewVehicles = new List<HSLVehicle>();

            //Client request to get the data from the HSL server 
            HttpClient httpClient = new HttpClient();
            httpClient.MaxResponseContentBufferSize = 512000;
            string uri = "http://dev.hsl.fi/siriaccess/vm/json?operatorRef=HSL&" + DateTime.Now.Ticks.ToString();
            HttpResponseMessage response = await httpClient.GetAsync(uri);
            try
            {
                response.EnsureSuccessStatusCode();
                Stream StreamResponse = await response.Content.ReadAsStreamAsync();
                DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(RootObject));
                RootObject returnedData = (RootObject)s.ReadObject(StreamResponse);
                if (returnedData.Siri.ServiceDelivery.VehicleMonitoringDelivery.Count == 1)
                {
                    try
                    {
                        CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
                        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            //Get the list of vehicles from the returned data
                            var AllVehicle = from m in returnedData.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity
                                             select m;
                            foreach (VehicleActivity singleVehicle in AllVehicle)
                            {
                                HSLVehicle hslVehicle = new HSLVehicle();
                                hslVehicle.LineRef = singleVehicle.MonitoredVehicleJourney.LineRef.value;
                                hslVehicle.VehicleRef = singleVehicle.MonitoredVehicleJourney.VehicleRef.value;

                                hslVehicle.Latitude = singleVehicle.MonitoredVehicleJourney.VehicleLocation.Latitude;
                                hslVehicle.Longitude = singleVehicle.MonitoredVehicleJourney.VehicleLocation.Longitude;

                                //Convert latitude and longitude to Geopoint
                                BasicGeoposition queryHint = new BasicGeoposition();
                                queryHint.Latitude = hslVehicle.Latitude;
                                queryHint.Longitude = hslVehicle.Longitude;
                                hslVehicle.Location = new Geopoint(queryHint);

                                //Add items to the observable collection
                                listOfNewVehicles.Add(hslVehicle);
                                //VehicleItems.Add(hslVehicle);
                            }
                            updateObservableCollectionVehicles(listOfNewVehicles);
                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            response.Dispose();
            httpClient.Dispose();
        }
开发者ID:nkeshri,项目名称:Jongla,代码行数:60,代码来源:HSLVehicleViewModel.cs

示例13: send

        /// <summary>
        /// Assincronouslly send the fields in the list to webServer in url parameter
        /// NextStep: add a percentage of uploaded data!
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        internal static async Task<string> send(List<field> fields, string url)
        {
            HttpClient httpClient = new HttpClient();
            MultipartFormDataContent form = new MultipartFormDataContent();

            foreach(field f in fields)
            {
                if(f.kind == fieldKind.text)
                {
                    form.Add(new StringContent(f.content), f.name);
                }
                else if (f.kind == fieldKind.file)
                {
                    HttpContent content = new ByteArrayContent(f.bytes);
                    content.Headers.Add("Content-Type", f.contentType);
                    form.Add(content, f.name, f.fileName);
                }
            }

            HttpResponseMessage response = await httpClient.PostAsync(url, form);

            response.EnsureSuccessStatusCode();
            httpClient.Dispose();
            return response.Content.ReadAsStringAsync().Result;
        }
开发者ID:luandev,项目名称:csharpFormPost,代码行数:32,代码来源:post.cs

示例14: GetResponseStringAsync

        // asynchronous function to validate token, to 
        // update token if necessary or to return false
        // if token is invalid
        public static async Task<String> GetResponseStringAsync(string field, Dictionary<string, string> dataPairs)
        {
            try
            {
                HttpClient client = new HttpClient();

                // http get request to validate token
                HttpResponseMessage response = await client.GetAsync(Utils.LAPI.GenerateGetURL(field, dataPairs));

                // make sure the http reponse is successful
                response.EnsureSuccessStatusCode();

                // convert http response to string
                string responseString = await response.Content.ReadAsStringAsync();

                response.Dispose();
                client.Dispose();

                return responseString;
            }
            catch
            {
                return null;
            }
        }
开发者ID:scottmeng,项目名称:ivle_metro_win8,代码行数:28,代码来源:RequestSender.cs

示例15: BitmapImageAsync

        public async Task<BitmapImage> BitmapImageAsync(string url)
        {
            Stream stream = null;
            HttpClient WebClient = new HttpClient();
            BitmapImage image = new BitmapImage();

            try
            {
                stream = new MemoryStream(await WebClient.GetByteArrayAsync(url));
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad; // here
                image.StreamSource = stream;
                image.EndInit();
                image.Freeze();
            }
            catch { }

            if (stream != null)
            {
                stream.Close(); stream.Dispose(); stream = null;
            }

            url = null; WebClient.CancelPendingRequests(); WebClient.Dispose(); WebClient = null;
            return image;
        }
开发者ID:korner-brazers,项目名称:VK-HashTag,代码行数:25,代码来源:DownloadImage.cs


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