/// <summary> /// WebApiPost请求 /// </summary> /// <param name="requestUrl">请求的Url地址</param> /// <param name="para">请求的参数</param> /// <param name="hasJson">是否为json</param> /// <returns>返回json</returns> public static string DoPost(string requestUrl, object para, bool hasJson = false) { string postUrl = requestUrl; var httpClient = new System.Net.Http.HttpClient(); try { var postPara = string.Empty; if (hasJson) { postPara = para.ToString(); } else { postPara = JsonConvert.SerializeObject(para); } System.Net.Http.HttpContent httpContent = new System.Net.Http.StringContent(postPara); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); string responseJson = httpClient.PostAsync(postUrl, httpContent).Result.Content.ReadAsStringAsync().Result; return(responseJson); } catch { return(""); } finally { //用完要记得释放 httpClient.Dispose(); } }
public static void DisposeHttpClient() { if (httpClient != null) { httpClient.Dispose(); } }
public static List <Station> LeerEstaciones() { List <Station> estaciones = new List <Station>(); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); var xmlStream = client.GetStreamAsync("http://radioudg.okhosting.com/virtuales.xml").Result; System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream); //extraer episodios del xml while (reader.ReadToFollowing("estacion")) { Station estacion = new Station(); reader.ReadToFollowing("imagen"); estacion.WebSiteUri = new Uri(reader.ReadElementContentAsString()); reader.ReadToFollowing("streaming"); estacion.StramingUri = new Uri(reader.ReadElementContentAsString()); reader.ReadToFollowing("nombre"); estacion.Name = reader.ReadElementContentAsString(); reader.ReadToFollowing("descripcion"); estacion.Description = reader.ReadElementContentAsString(); estaciones.Add(estacion); } reader.Dispose(); xmlStream.Dispose(); client.Dispose(); return(estaciones); }
/// <summary> /// Perform an HTTP GET request to a URL using an HTTP Authorization header /// </summary> /// <param name="url">The URL</param> /// <param name="token">The token</param> /// <returns>String containing the results of the GET operation</returns> public async Task <string> GetHttpContentWithToken(Uri url, string token, CancellationToken cancellationToken) { System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response; try { using (System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url)) { //Add the token in Authorization header request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(content); } } catch (Exception) { throw; } ///finally dla usuniecia warningu finally { httpClient.Dispose(); } }
protected virtual void Disposing(bool disposing) { if (disposing) { http.Dispose(); } }
///<inheritdoc/> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _client?.Dispose(); } }
private async void Post() { try { var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_books); var responseMessageesponse = await _client.GetAsync(Url); responseMessageesponse.EnsureSuccessStatusCode(); var body = System.Text.Encoding.UTF8.GetBytes(json); var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = body.Length; using (var stream = request.GetRequestStream()) { stream.Write(body, 0, body.Length); stream.Close(); } using (var response = (System.Net.HttpWebResponse)request.GetResponse()) { System.Console.WriteLine($"Status Code: {response.StatusCode}"); System.Console.WriteLine($"Method : {response.Method}"); response.Close(); } } catch (System.AggregateException aggregateException) { System.Console.WriteLine("\nException Caught!"); System.Console.WriteLine("Message :{0} ", aggregateException.Message); } catch (System.ObjectDisposedException disposedException) { System.Console.WriteLine("\nException Caught!"); System.Console.WriteLine("Message :{0} ", disposedException.Message); } catch (System.Threading.Tasks.TaskCanceledException exception) { System.Console.WriteLine("\nException Caught!"); System.Console.WriteLine("Message :{0} ", exception.Message); } catch (System.Net.Http.HttpRequestException e) { System.Console.WriteLine("\nException Caught!"); System.Console.WriteLine("Message :{0} ", e.Message); } catch (System.Net.WebException webException) { System.Console.WriteLine("\nException Caught!"); System.Console.WriteLine("Message :{0} ", webException.Message); } _client.Dispose(); }
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); }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { httpClient.Dispose(); } disposed = true; } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { NullPostContent.Dispose(); Web.Dispose(); } disposedValue = true; } }
protected void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects) _httpClient.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { _httpClient.Dispose(); _webClient.Dispose(); } disposed = true; }
/// <summary> /// GET Data /// </summary> /// <param name="topic"></param> /// <param name="data"></param> public static async Task <string> GETRequest(string httpAddress) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string responseData = string.Empty; try { System.Net.Http.HttpResponseMessage response = await client.GetAsync(httpAddress); response.EnsureSuccessStatusCode(); responseData = await response.Content.ReadAsStringAsync(); } catch (Exception e) { Console.WriteLine(e.Message); } finally { client.Dispose(); } return(responseData); }
// </HandleNotChanged> // <AwaitFinally> 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 void Main_WhenReports_ShouldStartProcessing() { // Arrange var testClient = new System.Net.Http.HttpClient(); var clientMock = new Mock <IClient>(); var generatorMock = new Mock <IGenerator>(); clientMock.Setup(cli => cli.RestClient).Returns(testClient); var systemUnderTest = new ReportTool(clientMock.Object, generatorMock.Object); // Act systemUnderTest.Main(AllReportsFile); // Assert clientMock.Verify(cli => cli.ScanAsync(It.IsAny <DataOptions>(), It.IsAny <IEnumerable <string> >(), It.IsAny <Uri>()), Times.Once); generatorMock.Verify(gen => gen.CreateReportsAsync(It.IsAny <IEnumerable <IReport> >(), It.IsAny <AzureDevOpsInstance>(), It.IsAny <string>()), Times.Once); testClient.Dispose(); }
/// <summary> /// POST Data /// </summary> /// <param name="topic"></param> /// <param name="jsonData">POST Data</param> public static async Task <string> POSTRequest(string httpAddress, string jsonData) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string responseData = string.Empty; try { System.Net.Http.HttpResponseMessage response = await client.PostAsync(httpAddress, new System.Net.Http.StringContent(jsonData, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); responseData = await response.Content.ReadAsStringAsync(); } catch (Exception e) { Console.WriteLine(e.Message); responseData = jsonData; } finally { client.Dispose(); } return(responseData); }
/// <inheritdoc /> public async Task BlockFriendsAsync(ISession session, IEnumerable <string> ids, IEnumerable <string> usernames = null) { // TODO //await _apiClient.BlockFriendsAsync(session.AuthToken, ids, usernames); var client = new System.Net.Http.HttpClient(); // FIXME var urlpath = "/v2/friend/block?"; foreach (var id in ids ?? new string[0]) { urlpath = string.Concat(urlpath, "ids=", id, "&"); } foreach (var username in usernames ?? new string[0]) { urlpath = string.Concat(urlpath, "usernames=", username, "&"); } var request = new System.Net.Http.HttpRequestMessage { RequestUri = new Uri(new UriBuilder(Secure ? "https" : "http", Host, Port).Uri, urlpath), Method = new System.Net.Http.HttpMethod("POST"), Headers = { Accept = { new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json") } } }; var header = string.Concat("Bearer ", session.AuthToken); request.Headers.Authorization = System.Net.Http.Headers.AuthenticationHeaderValue.Parse(header); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync(); client.Dispose(); }
/// <inheritdoc /> public async Task PromoteGroupUsersAsync(ISession session, string groupId, IEnumerable <string> ids) { // TODO //await _apiClient.PromoteGroupUsersAsync(session.AuthToken, groupId, ids); var client = new System.Net.Http.HttpClient(); // FIXME if (groupId == null) { throw new ArgumentException("'groupId' is required but was null."); } var urlpath = "/v2/group/{group_id}/promote?"; urlpath = urlpath.Replace("{group_id}", Uri.EscapeDataString(groupId)); foreach (var id in ids ?? new string[0]) { urlpath = string.Concat(urlpath, "ids=", id, "&"); } var request = new System.Net.Http.HttpRequestMessage { RequestUri = new Uri(new UriBuilder(Secure ? "https" : "http", Host, Port).Uri, urlpath), Method = new System.Net.Http.HttpMethod("POST"), Headers = { Accept = { new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json") } } }; var header = string.Concat("Bearer ", session.AuthToken); request.Headers.Authorization = System.Net.Http.Headers.AuthenticationHeaderValue.Parse(header); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync(); client.Dispose(); }
static async Task <string> HttpGetStrAsync(string url) { var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync(url); try { var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException ex) { await LogAsync($"失敗: {ex.Message}"); return(ex.Message); } finally { client.Dispose(); await LogAsync("離開 HttpGHetAsync() 方法。"); } }
// </HandleNotChanged> // <AwaitFinally> 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(); } }
protected async Task refreshToken() { debug("Requesting auth token..."); try { var client = new System.Net.Http.HttpClient(); var uriBuilder = new UriBuilder(Uri.UriSchemeHttps, HOST, PORT, "auth"); var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, uriBuilder.Uri); request.Headers.Authorization = getAuthenticationHeader(); request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new IntrinioRealtimeAuthorizationException(); } else if (!response.IsSuccessStatusCode) { throw new IntrinioRealtimeAuthorizationException($"Could not get auth token: Status code { Enum.GetName(typeof(System.Net.HttpStatusCode), response.StatusCode)}"); } else { this.token = await response.Content.ReadAsStringAsync(); this.debug("Received auth token!"); } client.Dispose(); } catch (Exception e) { this.error(new IntrinioRealtimeException("Something happened while loading token", e)); } }
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 { throw; } finally { wc.Dispose(); } }
/// <summary>Get our super-awesome curated tweets</summary> /// <param name="startDate">Earliest entry timestamp in UTC (inclusive, ie. '2018-03-20T04:07:56.271Z')</param> /// <param name="endDate">Latest entry timestamp in UTC (inclusive, ie. '2018-03-20T04:07:56.271Z')</param> /// <returns>Tweets with stamps between startDate and endDate</returns> /// <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 <System.Collections.ObjectModel.ObservableCollection <Tweet> > ApiV1TweetsGetAsync(System.DateTime startDate, System.DateTime endDate, System.Threading.CancellationToken cancellationToken) { if (startDate == null) { throw new System.ArgumentNullException("startDate"); } if (endDate == null) { throw new System.ArgumentNullException("endDate"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Tweets?"); urlBuilder_.Append("startDate=").Append(System.Uri.EscapeDataString(startDate.ToString("s", System.Globalization.CultureInfo.InvariantCulture))).Append("&"); urlBuilder_.Append("endDate=").Append(System.Uri.EscapeDataString(endDate.ToString("s", System.Globalization.CultureInfo.InvariantCulture))).Append("&"); urlBuilder_.Length--; 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")); 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(System.Collections.ObjectModel.ObservableCollection <Tweet>); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <Tweet> >(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_ == "400") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(System.Collections.Generic.Dictionary <string, string>); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.Generic.Dictionary <string, string> >(responseData_, _settings.Value); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } throw new SwaggerException <System.Collections.Generic.Dictionary <string, string> >("Invalid startDate and/or endDate", (int)response_.StatusCode, responseData_, headers_, result_, null); } else if (status_ == "500") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("Something went wrong!", (int)response_.StatusCode, responseData_, headers_, null); } 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(System.Collections.ObjectModel.ObservableCollection <Tweet>)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.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 <int> CheckCurrencyAsync(string apiKey, long accountId, System.Threading.CancellationToken cancellationToken) { if (accountId == null) { throw new System.ArgumentNullException("accountId"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Communication/CheckCurrency?"); urlBuilder_.Append("apiKey=").Append(System.Uri.EscapeDataString(apiKey != null ? System.Convert.ToString(apiKey, System.Globalization.CultureInfo.InvariantCulture) : "")).Append("&"); urlBuilder_.Append("accountId=").Append(System.Uri.EscapeDataString(System.Convert.ToString(accountId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); urlBuilder_.Length--; 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")); 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_ == "200") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(int); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <int>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception_); } } 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); } return(default(int)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
private async void btnCheck_Click(object sender, EventArgs e) { startStopWaiting(true); var url = getBaseUrl(txtBaseUrl.Text); 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 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; } var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); string result_; try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(responseData_); SetConnectionResult(true, result_); } catch (System.Exception) { SetConnectionResult(false, ""); } } else if (status_ != "200" && status_ != "204") { SetConnectionResult(false, ""); } } finally { if (response_ != null) { response_.Dispose(); } } } } catch (System.Exception) { SetConnectionResult(false, ""); } finally { if (client_ != null) { client_.Dispose(); } startStopWaiting(false); } }
/// <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 PutAsync(System.Guid basketId, AddItemToBasketRequest request, System.Threading.CancellationToken cancellationToken) { if (basketId == null) { throw new System.ArgumentNullException("basketId"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/{basketId}"); urlBuilder_.Replace("{basketId}", System.Uri.EscapeDataString(ConvertToString(basketId, System.Globalization.CultureInfo.InvariantCulture))); 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(request, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); 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") { return; } 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); } } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.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 <FileResponse> PostAsync(GetTokenRequest request, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/generate"); 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(request, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); 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" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, client_, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(fileResponse_); } 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(FileResponse)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
public static List<Station> LeerEstaciones() { List<Station> estaciones = new List<Station>(); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); var xmlStream = client.GetStreamAsync("http://radioudg.okhosting.com/virtuales.xml").Result; System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream); //extraer episodios del xml while (reader.ReadToFollowing("estacion")) { Station estacion = new Station(); reader.ReadToFollowing("imagen"); estacion.WebSiteUri = new Uri(reader.ReadElementContentAsString()); reader.ReadToFollowing("streaming"); estacion.StramingUri = new Uri(reader.ReadElementContentAsString()); reader.ReadToFollowing("nombre"); estacion.Name = reader.ReadElementContentAsString(); reader.ReadToFollowing("descripcion"); estacion.Description = reader.ReadElementContentAsString(); estaciones.Add(estacion); } reader.Dispose(); xmlStream.Dispose(); client.Dispose(); return estaciones; }
public override void Start() { base.Start(); IRelativePanel panel = Platform.Current.Create<IRelativePanel>(); panel.BackgroundColor = new Color (255, 255, 255, 255); IGrid grdMenu = Constantes.CrearMenuVacio(); panel.Add(grdMenu, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.TopWith); IImageButton imgHome = Platform.Current.Create<IImageButton>(); imgHome.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images/app-15.png")); imgHome.Click += cmdHome_Click; grdMenu.SetContent(1, 0, imgHome); IImageButton imgRegionales = Platform.Current.Create<IImageButton>(); imgRegionales.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-11.png")); imgRegionales.Click += cmdEstaciones_Click; grdMenu.SetContent(1, 1, imgRegionales); IImageButton cmdProgramas = Platform.Current.Create<IImageButton>(); cmdProgramas.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-08.png")); //cmdProgramas.Click += (object sender, EventArgs e) => new ProgramasController().Start(); grdMenu.SetContent(1, 2, cmdProgramas); IImageButton imgVirtuales = Platform.Current.Create<IImageButton>(); imgVirtuales.LoadFromUrl (new Uri("http://radioudg.okhosting.com/images-old/icon-09.png")); imgVirtuales.Click += cmdVirtuales_Click; grdMenu.SetContent(1, 3, imgVirtuales); ILabel lblTitulo = Constantes.CrearTitulo("Archivo de programa", new Color(255, 255, 143, 0)); panel.Add(lblTitulo, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, grdMenu); if (Platform.Current.Page.Width > 250) { IImage imgLogo = Platform.Current.Create<IImage> (); imgLogo.LoadFromUrl (new Uri ("http://radioudg.okhosting.com/images-old/icon2--14.png")); imgLogo.Width = Platform.Current.Page.Width / 6; imgLogo.Height = lblTitulo.Height; imgLogo.Margin = new Thickness (0, 0, 10, 0); panel.Add(imgLogo, RelativePanelHorizontalContraint.RightWith, RelativePanelVerticalContraint.TopWith, lblTitulo); } System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); var xmlStream = client.GetStreamAsync(Show.PodcastUri).Result; System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlStream); IList<Episode> episodios = new List<Episode>(); //extraer episodios del xml while (reader.ReadToFollowing ("item")) { reader.ReadToFollowing ("title"); Episode episodio = new Episode (); episodio.Name = reader.ReadElementContentAsString (); reader.ReadToFollowing ("link"); string mp3string = reader.ReadElementContentAsString(); episodio.EpisodeUri = new Uri (mp3string); episodio.ImagenUri = Show.LogoUri; episodio.Description = Show.Name; episodios.Add (episodio); } reader.Dispose(); xmlStream.Dispose(); client.Dispose(); IControl referencia = lblTitulo; foreach (Episode episodio in episodios) { IImageButton imgLogo = Platform.Current.Create<IImageButton>(); imgLogo.LoadFromUrl(Show.LogoUri); imgLogo.Click += Episode_Click; imgLogo.Tag = episodio; imgLogo.Width = Constantes.AnchoIconos; imgLogo.Height = Constantes.AnchoIconos; //set margin for first iteration if (referencia == lblTitulo) { imgLogo.Margin = new Thickness(10, 10, 10, 10); } else { imgLogo.Margin = new Thickness(0, 10, 10, 10); } panel.Add(imgLogo, RelativePanelHorizontalContraint.LeftWith, RelativePanelVerticalContraint.BelowOf, referencia); referencia = imgLogo; ILabelButton lblNombre = Platform.Current.Create<ILabelButton> (); lblNombre.Click += Episode_Click; lblNombre.Text = episodio.Name; lblNombre.Tag = episodio; lblNombre.Bold = true; lblNombre.FontSize = Constantes.FontSize2; lblNombre.FontColor = Constantes.FontColor2; lblNombre.Width = Platform.Current.Page.Width - (Constantes.AnchoIconos * 3) + 10; panel.Add (lblNombre, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, imgLogo); IImageButton imgPlay = Platform.Current.Create<IImageButton>(); imgPlay.LoadFromUrl(new Uri ("http://radioudg.okhosting.com/images-old/icon-20.png")); imgPlay.Click += Episode_Click; imgPlay.Tag = episodio; imgPlay.Width = Constantes.AnchoIconos; imgPlay.Height = Constantes.AnchoIconos; panel.Add(imgPlay, RelativePanelHorizontalContraint.RightOf, RelativePanelVerticalContraint.TopWith, lblNombre); } Platform.Current.Page.Title = "Selecciona un episodio"; Platform.Current.Page.Content = panel; }
/// <summary> /// 连接关闭 /// </summary> /// <returns>是否关闭成功</returns> public void Close() { transport.Dispose(); }
public void Dispose() { client.Dispose(); }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task <System.Collections.ObjectModel.ObservableCollection <WeatherForecast> > WeatherForecastsAsync(System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/api/SampleData/WeatherForecasts"); 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")); 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_ == "200") { var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(System.Collections.ObjectModel.ObservableCollection <WeatherForecast>); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ObjectModel.ObservableCollection <WeatherForecast> >(responseData_, new Newtonsoft.Json.JsonSerializerSettings { PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All }); return(result_); } catch (System.Exception exception) { throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, headers_, exception); } } 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); } return(default(System.Collections.ObjectModel.ObservableCollection <WeatherForecast>)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { if (client_ != null) { client_.Dispose(); } } }
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> public async System.Threading.Tasks.Task DeleteShopAsync(System.Guid id, System.Collections.Generic.IEnumerable <string> additionalIds, System.Threading.CancellationToken cancellationToken) { if (id == null) { throw new System.ArgumentNullException("id"); } var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl).Append("/api/SampleData?"); urlBuilder_.Append("id=").Append(System.Uri.EscapeDataString(id.ToString())).Append("&"); urlBuilder_.Length--; var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Headers.TryAddWithoutValidation("additionalIds", additionalIds); request_.Method = new System.Net.Http.HttpMethod("DELETE"); 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_ == "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(); } } }