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; } } }
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; }
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(); }); }
// 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; } }
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(); }
public async Task <T> PutClient <T>(string resource, string jsonRequest = "") { T result = default(T); await Task.Run(async() => { var client = new System.Net.Http.HttpClient(new NativeMessageHandler()); client.BaseAddress = baseUrl; if (!string.IsNullOrWhiteSpace(App.Token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.Token); } var content = new StringContent(jsonRequest, Encoding.UTF8, "text/json"); var response = await client.PutAsync(resource, content); var responseJson = response.Content.ReadAsStringAsync().Result; result = JsonConvert.DeserializeObject <T>(responseJson); client.Dispose(); if (result == null) { throw new Exception(); } }); return(result); }
public static async Task <string> MakeRequestAndLogFailures() { await logMethodEntrance(); var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync("https://localhost:10000"); try { var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await logError("Recovered from redirect", e); return("Site Moved"); } finally { await logMethodExit(); client.Dispose(); } }
public static async Task <string> MakeRequestAndLogFailures() { //The implementation details for adding await support inside catch and finally //clauses ensure that the behavior is consistent with the behavior for synchronous code. //When code executed in a catch or finally clause throws, execution looks for a suitable //catch clause in the next surrounding block.If there was a current exception, that exception //is lost.The same happens with awaited expressions in catch and finally clauses: //a suitable catch is searched for, and the current exception, if any, is lost. await LogMethodEntrance(); var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync("https://localHost:10000"); try { var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await LogError("Recovered from redirect", e); return("Site Moved"); } finally { await LogMethodExit(); client.Dispose(); } }
public static async Task SendEventHubEventAsync(TemperatureData temperatureData) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Clear(); var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue( "SharedAccessSignature", SAS); client.DefaultRequestHeaders.Authorization = authHeader; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TemperatureData)); string body = string.Empty; using (MemoryStream ms = new MemoryStream()) using (StreamReader sr = new StreamReader(ms)) { serializer.WriteObject(ms, temperatureData); ms.Seek(0, SeekOrigin.Begin); body = sr.ReadToEnd(); } StringContent content = new StringContent(body, Encoding.UTF8); client.BaseAddress = new Uri(BaseUri); //await client.PostAsync(ServiceUri, content); client.Dispose(); }
public void Dispose() { if (_httpClient != null) { _httpClient.Dispose(); } }
public static Task<FileInfo> DownloadFile(DirectoryInfo tempDir, Uri distributiveUri) { var httpClient = new HttpClient(); var requestMessage = new HttpRequestMessage(HttpMethod.Get, distributiveUri); return httpClient .SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead) .ContinueWith( getDistributiveTask => { var response = getDistributiveTask.Result; response.EnsureSuccessStatusCode(); var downloadingFileName = string.Format("{0}.{1}.zip", Guid.NewGuid(), distributiveUri.Segments.LastOrDefault() ?? string.Empty); var tempFile = new FileInfo(Path.Combine(tempDir.FullName, downloadingFileName)); var tempFileWriteStream = tempFile.OpenWrite(); return response.Content .CopyToAsync(tempFileWriteStream) .ContinueWith( copyTask => { copyTask.Wait(); // ensuring exception propagated (is it nessesary?) tempFileWriteStream.Close(); return tempFile; }); }) .Unwrap() .ContinueWith( downloadTask => { httpClient.Dispose(); return downloadTask.Result; }); }
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; }
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}&password={1}&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; }
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; }
private async Task <string> SendMessage(string message) { String querys = "question=" + message; String url = host + path; string reply; if (0 < querys.Length) { url = url + "?" + querys; } HttpClient client = new System.Net.Http.HttpClient(); try { client.DefaultRequestHeaders.Add("Authorization", "APPCODE " + appcode); var reponse = await client.GetStreamAsync(url); var streamReader = new StreamReader(reponse, Encoding.UTF8); reply = streamReader.ReadToEnd(); }catch (Exception err) { reply = err.Message; } finally { client.Dispose(); } return(reply); }
/// <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; }
} // 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
public async static void UploadToServer(DataSample element) { var httpClient = new System.Net.Http.HttpClient(); try { string resourceAddress = "http://localhost:4848/WCFService.svc/GetData"; var result = Newtonsoft.Json.JsonConvert.SerializeObject(element); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); System.Net.Http.HttpResponseMessage wcfResponse = await httpClient.PostAsync(resourceAddress, new StringContent(result, Encoding.UTF8, "application/json")); } catch (HttpRequestException) { } catch (TaskCanceledException) { } catch (Exception ex) { } finally { if (httpClient != null) { httpClient.Dispose(); httpClient = null; } } }
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; }
//9.await in catch finally block public async Task <string> AwaitInCatchFinallyBlock() { var client = new System.Net.Http.HttpClient(); try { await logger.Log("Enter the " + nameof(AwaitInCatchFinallyBlock)); var streamTask = client.GetStringAsync("https://localHost:10000"); var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await logger.Log("Recovered from redirect", e); return("Site Moved"); } finally { await logger.Exit(); client.Dispose(); } }
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; }
public void Dispose() { if (createdClient) { client?.Dispose(); } }
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; }
public static async Task <HttpResponseMessage> PutAsync(this System.Net.Http.HttpClient client, object data) { var putData = Newtonsoft.Json.JsonConvert.SerializeObject(data); using (HttpContent httpContent = new StringContent(putData, Encoding.UTF8)) { var clientDefaultHeaders = client.DefaultRequestHeaders .FirstOrDefault(o => o.Key.ToLower().Equals("content-type")) .Value.FirstOrDefault() ?? ""; if (!string.IsNullOrEmpty(clientDefaultHeaders)) { httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(clientDefaultHeaders); ; } else { httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(HttpClientContext.DefaultContentType); ; } SetHiSecuritySignHeader(client, httpContent, data, "put"); var response = await client.PutAsync(client.BaseAddress, httpContent); WriteClientLog(client.BaseAddress.AbsoluteUri, "Put:" + client.BaseAddress.AbsoluteUri, httpContent.GetSerializeObject(), response.Content.ReadAsStringAsync().Result); client.Dispose(); return(response); } }
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; } }
//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; } }
static ProductViewModel getProduct(int id) { HttpClient client = new HttpClient(); HttpResponseMessage response = client.GetAsync(baseURL + "api/Products/" + id).Result; client.Dispose(); return response.Content.ReadAsAsync<ProductViewModel>().Result; }
static void DeleteProduct(int id) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseURL); var relativeUri = "api/Products/" + id.ToString(); var response = client.DeleteAsync(relativeUri).Result; client.Dispose(); }
public static IEnumerable<ProductViewModel> getTopProducts() { HttpClient client = new HttpClient(); HttpResponseMessage response = client.GetAsync("http://localhost:30000/api/Products/1").Result; client.Dispose(); return response.Content.ReadAsAsync<IEnumerable<ProductViewModel>>().Result; }
public void Dispose() { try { _client?.Dispose(); _client = null; } catch (ObjectDisposedException) { } }
//DELETEコマンドの実行 static async void DeleteHero(int id) { var client = new HttpClient(); //DELETEコマンドを非同期で実行 Console.WriteLine("== Delete Hero ID : {0} ==", id); var url = string.Format("http://localhost:35833/api/heroes?id={0}", id); var response = await client.DeleteAsync(url); Console.WriteLine("--DELETE Result Status Code--"); Console.WriteLine("Status: {0}", (int)response.StatusCode); client.Dispose(); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_httpClient != null) { _httpClient.Dispose(); } } }
private void CreateOrConfigureHttpClient(HummClientConfiguration config) { System.Net.Http.HttpClientHandler?handler = null; try { if (config.HttpClient == null) { handler = new System.Net.Http.HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate; } _Client = new System.Net.Http.HttpClient(handler); } else { _Client = config.HttpClient; } _Client.BaseAddress = _BaseUrl; if (String.IsNullOrEmpty(config.UserAgentProductName) || String.IsNullOrEmpty(config.UserAgentProductVersion)) { _Client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("Yort.Humm.Instore", typeof(HummClient).Assembly.GetName().Version.ToString())); } else { _Client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(config.UserAgentProductName, config.UserAgentProductVersion)); _Client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("(Yort.Humm.Instore/" + typeof(HummClient).Assembly.GetName().Version.ToString() + ")")); } } catch { handler?.Dispose(); if (_Config.HttpClient == null) { _Client?.Dispose(); } throw; } }
private string GetContent(string uri) { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response = httpClient.GetAsync(uri).Result; string content = response.Content.ReadAsStringAsync().Result; response.Dispose(); httpClient.Dispose(); return(content); }
// // Disposable implementation // #region protected virtual void Dispose(bool disposing) /// <summary> /// Primary disposal method to release reasources, inheritors should override to /// dispose of any unmanaged resources, calling the base implementation afterwards. /// </summary> /// <param name="disposing">true if this was called from the public Dispose method</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (null != _client && _ownsClient) { _client.Dispose(); } } _client = null; }
private async void Button_Click(object sender, RoutedEventArgs e) { if (lightrjinstcode.Text.Length == 10) { if (twitteronoff.IsOn == true) { Notificar.IsEnabled = false; FlipEnergia.SelectedValue = FlipEnergiaStatus; StatusEnergia.Text = "Notificando interrupção de serviço da light... " + "(" + lightrjinstcode.Text + ")"; StatusEnergiaProgress.IsActive = true; //função que conecta na nuvem para pegar os dados necessários //vamos começar pelo simulador... if (ToggleSimulador.IsOn == true) { HttpClient client = new HttpClient(); //http via post pq é um dos requerimentos do api. try { var contents = new StringContent(""); var response = await client.PostAsync("http://localhost/simuladorApi.php",contents); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); StatusEnergia.Text = responseBody; if (response.IsSuccessStatusCode) { //Windows API não dá suporte a JSON então tem q fazer o proprio parser. StatusEnergia.Text = StatusEnergia.Text.Substring((StatusEnergia.Text.LastIndexOf("text") + 8)); StatusEnergia.Text = StatusEnergia.Text.Remove((StatusEnergia.Text.Length - 2)); StatusEnergiaProgress.IsActive = false; //tb não dá tempo de fazer uma UI até a feira. } } catch { //ainda tem q fazer o catch mas ainda tenho q fazer o tcc! } client.Dispose(); } } } else { SacnetPivot.SelectedItem = PivotItemContas; FlipviewContas.SelectedItem = FlipViewItemContas; Prosseguir.Visibility = Visibility.Visible; Prosseguir.IsEnabled = true; } }
protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { var hc = new HttpClient(); var task = hc .PostAsync(context.GetValue(网址), context.GetValue(Http内容)) .ToApm(callback, state); task.ContinueWith(q => hc.Dispose() ); return task; }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { httpClient.Dispose(); } disposed = true; } }
private async Task<bool> RecaptchaIsValid(string captchaResponse) { var requestUrl = String.Format( "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", "6LcdQgkTAAAAAIKMbGwc-ZN5ubqhDsh3bF9Lpgy2", captchaResponse); string result = null; //HttpHandler HttpClientHandler myHandler = new HttpClientHandler(); myHandler.UseProxy = true; myHandler.Proxy = WebRequest.GetSystemWebProxy(); System.Diagnostics.Debug.WriteLine("Proxy: " + myHandler.Proxy.ToString()); //HttpClient using (var client = new HttpClient(myHandler)) { var serverResult = await client.GetStringAsync(requestUrl); result = serverResult.ToString(); client.Dispose(); } /* var httpClient = new HttpClient(myHandler); try { var serverResult = await httpClient.GetStringAsync(requestUrl); result = serverResult.ToString(); httpClient.Dispose(); } catch(Exception ex) { httpClient.Dispose(); System.Diagnostics.Debug.WriteLine("ERROR: " + ex.ToString()); }*/ if (!String.IsNullOrWhiteSpace(result)) { var obj = JsonConvert.DeserializeObject<RecaptchaResponse>(result); if (obj.Success) { return true; } } return false; }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _http.Dispose(); _client.Dispose(); } disposedValue = true; } }
//POSTコマンドの実行 static async void AddHero() { var client = new HttpClient(); string name = "仮面ライダーアギト"; //POSTコマンドをJSONを指定して非同期で実行 HttpResponseMessage response = await client.PostAsJsonAsync<string>("http://localhost:35833/api/heroes", name); Console.WriteLine("--POST resut--"); Console.WriteLine("Status: {0}", (int)response.StatusCode); if (response.IsSuccessStatusCode) { string m = await response.Content.ReadAsStringAsync(); Console.WriteLine(m); } client.Dispose(); }
public static Task<IEnumerable<Car>> GetCarsAsync() { var uri = "http://localhost:12941/api/cars"; var tcs = new TaskCompletionSource<IEnumerable<Car>>(); HttpClient client = new HttpClient(); return client.GetAsync(uri).Then<HttpResponseMessage, IEnumerable<Car>>(response => { // Note the best way to handle this but will do the work response.EnsureSuccessStatusCode(); return response.Content.ReadAsAsync<IEnumerable<Car>>().Then<IEnumerable<Car>, IEnumerable<Car>>(cars => { try { tcs.SetResult(cars); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; }, runSynchronously: true).Catch<IEnumerable<Car>>(info => { tcs.SetException(info.Exception); return new CatchInfoBase<Task<IEnumerable<Car>>>.CatchResult { Task = tcs.Task }; }).Finally(() => client.Dispose(), runSynchronously: true); }, runSynchronously: true).Catch<IEnumerable<Car>>(info => { client.Dispose(); tcs.SetException(info.Exception); return new CatchInfoBase<Task<IEnumerable<Car>>>.CatchResult { Task = tcs.Task }; }); }
private void CalculateAsyncTplOnlyCorrect() { ProgressBar.IsIndeterminate = true; var client = new HttpClient(); client.GetStringAsync("http://www.google.com") .ContinueWith(t => { Application.Current.Dispatcher.BeginInvoke((Action)(() => { ProgressBar.IsIndeterminate = false; ResultTextBlock.Text = t.Result; })); client.Dispose(); }); }
/// <summary> /// Metoda pro získávání dat z Nominatimu. /// </summary> public bool GetData(double Latitude, double Longitude) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://nominatim.openstreetmap.org/"); var response = client.GetAsync("reverse?lat=" + Latitude.ToStringWithADot() + "&lon=" + Longitude.ToStringWithADot() + "&format=json&addressdetails=1").Result; if (response.StatusCode == HttpStatusCode.NotFound) return false; else { responseRoot = JsonConvert.DeserializeObject<NominatimResponseRoot>(response.Content.ReadAsStringAsync().Result); return true; } client.Dispose(); }
public void Dispose() { if (client != null) { client.Dispose(); client = null; } if (clientHandler != null) { clientHandler.Dispose(); clientHandler = null; } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _httpClient.Dispose(); } _disposed = true; }
// // Copy/Paste Sample: http://open.mapquestapi.com/nominatim/v1/reverse?format=xml&lat=51.521435&lon=-0.162714 // public async Task<GeocodeResult> ReverseGeocode(double latitude, double longitude) { string URL = String.Format( "http://open.mapquestapi.com/nominatim/v1/reverse?format=xml&lat={0}&lon={1}", latitude.ToString(CultureInfo.InvariantCulture), longitude.ToString(CultureInfo.InvariantCulture)); string response = ""; using (var client = new HttpClient()) { response = await client.GetStringAsync(URL); client.Dispose(); } var searchresults = XElement.Parse(response); var resElement = searchresults.Elements("result").FirstOrDefault(); var addressElement = searchresults.Elements("addressparts").FirstOrDefault(); if (resElement != null && addressElement != null) { var countryCode = (string)addressElement.Element("country_code"); if (0 == String.Compare("at", countryCode, StringComparison.OrdinalIgnoreCase)) { // Only if City or Town is not available, we will fall back to the actual location name string locationName = (string)addressElement.Element("city"); if (String.IsNullOrWhiteSpace(locationName)) { locationName = (string)addressElement.Element("town"); if (String.IsNullOrWhiteSpace(locationName)) { locationName = (string)resElement; } } var result = new GeocodeResult() { Name = locationName, Latitude = MappingHelpers.ConvertDouble((string) resElement.Attribute("lat")), Longitude = MappingHelpers.ConvertDouble((string) resElement.Attribute("lon")) }; return result; } } return null; }
/// <summary> /// delete async /// </summary> /// <param name="client"></param> /// <returns></returns> public static async Task <HttpContent> DeleteAsync(this System.Net.Http.HttpClient client) { if (client.DefaultRequestHeaders?.Contains("isHik") ?? false) { client.DefaultRequestHeaders.SetHikSecurityHeaders(null, client.BaseAddress.AbsoluteUri, null, "delete"); } var response = await client.DeleteAsync(client.BaseAddress); WriteClientLog(client.BaseAddress.AbsoluteUri, "Delete:" + client.BaseAddress.AbsoluteUri, client.DefaultRequestHeaders.GetSerializeObject(), response.Content.ReadAsStringAsync().Result); client.Dispose(); return(response.Content); }
public async static Task <List <Tuple <string, Point> > > GetShuttles(List <string> routeIDs) { if (!IsThereInternet()) { return(null); } string routeStr = ""; foreach (string route in routeIDs) { routeStr += route + ","; } // Download stops and get json response string url = "http://api.transloc.com/1.1/vehicles.json?agencies=" + agency + "&routes=" + routeStr; var client = new System.Net.Http.HttpClient(); HttpResponseMessage response = client.GetAsync(url).Result; string responseString = await response.Content.ReadAsStringAsync(); JsonObject obj = JsonObject.Parse(responseString); var derp = obj["data"].GetObject(); var derp2 = derp[agency].GetArray(); List <Tuple <string, Point> > locsWithIDs = new List <Tuple <string, Point> >(); foreach (JsonValue val in derp2) { var vehicleObj = val.GetObject(); var loc = vehicleObj["location"].GetObject(); double lat = loc["lat"].GetNumber(); double lng = loc["lng"].GetNumber(); string routeID = vehicleObj["route_id"].GetString(); locsWithIDs.Add(Tuple.Create <string, Point>(routeID, new Point(lat, lng))); } // cleanup obj = null; response.Dispose(); response = null; client.Dispose(); client = null; return(locsWithIDs); }
/// <summary> /// Method to use System.Net.Http.HttpClient's GetAsync method /// </summary> /// <param name="baseUrl">base url</param> /// <param name="contentUrl">rest of url</param> /// <param name="accessToken">access token</param> /// <param name="accessTokenType">access token type</param> /// <returns>responseContent</returns> /// <exception cref="HttpRequestException">Exception will be when request server is closed</exception> public async Task <string> GetAsync(string baseUrl, string contentUrl, string accessToken, string accessTokenType) { try { _client = new System.Net.Http.HttpClient(); _logger.Debug("Promact url : " + baseUrl); _client.BaseAddress = new Uri(baseUrl); // Added access token to request header if provided by user if (!String.IsNullOrEmpty(accessToken)) { _logger.Debug("Access token is not null" + accessToken); if (accessTokenType == _stringConstant.Bearer) { _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(_stringConstant.Bearer, accessToken); } else { _client.DefaultRequestHeaders.Add(accessTokenType, accessToken); } } _logger.Debug("ContentUrl : " + contentUrl); var response = _client.GetAsync(contentUrl).Result; _client.Dispose(); string responseContent = null; _logger.Debug("Status code : " + response.StatusCode); _logger.Debug("Return content : " + responseContent); if (response.StatusCode == System.Net.HttpStatusCode.OK) { responseContent = await response.Content.ReadAsStringAsync(); } return(responseContent); } catch (HttpRequestException ex) { _logger.Error("Error in HttpRequest : " + ex.Message + Environment.NewLine + ex.StackTrace); throw new Exception(_stringConstant.HttpRequestExceptionErrorMessage); } }
private async static Task <JsonObject> GetSegments() { if (!IsThereInternet()) { return(null); } string url = "http://api.transloc.com/1.1/segments.json?agencies=" + agency; var client = new System.Net.Http.HttpClient(); HttpResponseMessage response = client.GetAsync(url).Result; string responseString = await response.Content.ReadAsStringAsync(); JsonObject obj = JsonObject.Parse(responseString); JsonObject segmentArr = obj["data"].GetObject(); // clean up response.Dispose(); response = null; client.Dispose(); client = null; return(segmentArr); }
/// <summary> /// Method to use System.Net.Http.HttpClient's PostAsync method /// </summary> /// <param name="baseUrl">base url</param> /// <param name="contentString">text to be send</param> /// <param name="contentHeader">content header</param> /// <param name="accessToken">access token</param> /// <param name="accessTokenType">access token type</param> /// <returns>responseString</returns> /// <exception cref="HttpRequestException">Exception will be when request server is closed</exception> public async Task <string> PostAsync(string baseUrl, string contentString, string contentHeader, string accessToken, string accessTokenType) { try { _client = new System.Net.Http.HttpClient(); if (!string.IsNullOrEmpty(accessToken)) { _client.DefaultRequestHeaders.Add(accessTokenType, accessToken); } var response = await _client.PostAsync(baseUrl, new StringContent(contentString, Encoding.UTF8, contentHeader)); _client.Dispose(); string responseString = null; if (response.StatusCode == System.Net.HttpStatusCode.OK || response.StatusCode == System.Net.HttpStatusCode.Created) { responseString = response.Content.ReadAsStringAsync().Result; } return(responseString); } catch (HttpRequestException) { throw new Exception(_stringConstant.HttpRequestExceptionErrorMessage); } }
public static string[] Stems(string text) { //HttpClientHandler httpClientHandler = new HttpClientHandler() //{ // Proxy = new WebProxy(string.Format("{0}:{1}", "127.0.0.1", 8888), false) //}; var wc = new System.Net.Http.HttpClient(); try { var data = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.ToString(text)); var res = wc.PostAsync(classificationBaseUrl() + "/text_stemmer?ngrams=1", data).Result; return(Newtonsoft.Json.JsonConvert.DeserializeObject <string[]>(res.Content.ReadAsStringAsync().Result)); } catch (Exception e) { throw; } finally { wc.Dispose(); } }
/// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <TokenDTO> CreateAsync(TokenCreationDTO dto, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/token"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var formDataDictionary = new Dictionary <string, string>() { { "client_id", dto.Client_id }, { "username", dto.Username }, { "password", dto.Password }, { "grant_type", "password" } }; var formData = new FormUrlEncodedContent(formDataDictionary); //var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dto, _settings.Value)); var content_ = formData; content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(TokenDTO); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenDTO>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(TokenDTO)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
public void Dispose() { _httpClient.Dispose(); }
private async Task <bool> CheckConnection() { var url = Properties.Settings.Default.OrphanageServiceURL; if (!url.EndsWith("/")) { url += "/"; } url += "api/info/version"; var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); request_.RequestUri = new System.Uri(url, System.UriKind.RelativeOrAbsolute); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead); try { var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return(true); } } catch { return(false); } finally { if (response_ != null) { response_.Dispose(); } } } } catch (HttpRequestException requestException) { if (requestException.InnerException is WebException) { WebException webException = (WebException)requestException.InnerException; if (webException.HResult == -2146233079) { //SecurityProtocol is false var protocols = Enum.GetValues(typeof(SecurityProtocolType)); foreach (SecurityProtocolType pro in protocols) { if (pro != ServicePointManager.SecurityProtocol && !_ProtocolsList.Contains(pro)) { ServicePointManager.SecurityProtocol = pro; _ProtocolsList.Add(pro); break; } } } } return(false); } catch (System.Exception ex) { return(false); } finally { if (client_ != null) { client_.Dispose(); } } return(false); }
/// <summary>Add new entries.</summary> /// <param name="body">Entries to be uploaded.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Rejected list of entries. Empty list is success.</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task AddDeviceStatusAsync(System.Collections.Generic.IEnumerable <DeviceStatus> body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/devicestatus"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body)); // content_.Headers.ContentType.MediaType = "application/json"; content_.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); request_.Content = content_; request_.Method = HttpMethod.Post;// new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "405") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("Invalid input", status_, responseData_, headers_, null); } else if (status_ == "200") { return; } else if (status_ != "200" && status_ != "204") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
public void Dispose() { _httpClient?.Dispose(); _handler?.Dispose(); }
public void Dispose() { client?.Dispose(); }
public void Register(string username) { try { client = new HttpClient(); var postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("email", username)); HttpContent content = new FormUrlEncodedContent(postData); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); client.PostAsync("http://localhost:3000/User", content) .ContinueWith(postTask => { postTask.Result.EnsureSuccessStatusCode(); client.Dispose(); }); } catch (Exception ex) { } }