private static async Task <HttpContent> GetCompressedContent(HttpContent originalContent)
        {
            var ms = new System.IO.MemoryStream();

            try
            {
                await CompressOriginalContentStream(originalContent, ms).ConfigureAwait(false);

                ms.Seek(0, System.IO.SeekOrigin.Begin);

                var compressedContent = new StreamContent(ms);
                originalContent.CopyHeadersTo(compressedContent);
                compressedContent.Headers.ContentEncoding.Clear();
                compressedContent.Headers.ContentEncoding.Add("gzip");
                compressedContent.Headers.ContentLength = ms.Length;

                originalContent.Dispose();

                return(compressedContent);
            }
            catch
            {
                ms?.Dispose();
                throw;
            }
        }
        public async Task <T> PutAsync <T>(string endPointName, string url, object dataToSend, string mediaType)
        {
            T                   result;
            var                 httpResult          = string.Empty;
            HttpClient          httpClient          = null;
            HttpContent         httpContent         = null;
            HttpResponseMessage httpResponseMessage = null;

            try
            {
                var errorHttp = false;
                using (httpClient = GetDefaultClient(endPointName))
                {
                    httpContent         = CreateJsonHttpContent(dataToSend, mediaType);
                    httpResponseMessage = await httpClient.PutAsync(httpClient.BaseAddress + url, httpContent).ConfigureAwait(false);

                    if (httpResponseMessage?.IsSuccessStatusCode == true)
                    {
                        httpResult = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        errorHttp = true;
                    }

                    httpClient          = null;
                    httpResponseMessage = null;
                    httpContent         = null;

                    if (errorHttp)
                    {
                        throw new HttpRequestException($"The httprequest to {endPointName} was not successful.");
                    }

                    result = JsonConvert.DeserializeObject <T>(httpResult);
                }
            }
            catch (Exception ex)
            {
                LogException(ref ex);
                throw;
            }
            finally
            {
                if (httpClient != null)
                {
                    httpClient.Dispose();
                }
                if (httpContent != null)
                {
                    httpContent.Dispose();
                }
                if (httpResponseMessage != null)
                {
                    httpResponseMessage.Dispose();
                }
            }

            return(result);
        }
Example #3
0
        /// <summary>
        /// 获取repsonse结果
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="response">response</param>
        /// <returns></returns>
        public static T GetJsonResult <T>(this HttpContent response)
        {
            var data = response.ReadAsStringAsync().Result;

            response.Dispose();
            return(JsonConvert.DeserializeObject <T>(data));
        }
Example #4
0
 /// <summary>
 ///     Dispose of resources being used by the <see cref="ProgressContent"/>.
 /// </summary>
 /// <param name="disposing">
 ///     Explicit disposal?
 /// </param>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _innerContent.Dispose();
     }
 }
Example #5
0
        /// <summary>
        /// Attempts to download a file.
        /// </summary>
        /// <param name="url">The URL to downlaod from.</param>
        /// <param name="path">The path to store the file.</param>
        /// <returns>Boolean indicating the operation's success.</returns>
        public static bool TryDownloadFile(string url, string path)
        {
            HttpClient          cli  = new();
            HttpRequestMessage  req  = new(HttpMethod.Get, url);
            HttpResponseMessage resp = cli.Send(req);

            cli.Dispose();
            req.Dispose();

            if (!resp.IsSuccessStatusCode)
            {
                return(false);
            }

            try
            {
                HttpContent cont = resp.Content;
                FileStream  file = File.OpenWrite(path);
                cont.ReadAsStream().CopyTo(file);
                cont.Dispose();
                file.Close();
            }
            catch { return(false); }

            resp.Dispose();

            return(true);
        }
        public async Task Atualizar_Produto_Com_Imagem_Grande_Com_Erro_Por_Propriedades_Invalidas()
        {
            // Arrange
            FornecedorViewModel fornecedorVM = FornecedorViewModelTestsHelper.ObterInstancia(2, "40405549000180");

            (ProdutoImagemViewModel produtoVM, Stream imageStream) = ProdutoViewModelTestsHelper.ObterInstanciaParaImagemGrande(fornecedorVM, $"{base.Factory.Env.WebRootPath}/img");

            await AdicionarObjsParaTestes(fornecedorVM, ProdutoViewModelTestsHelper.ObterInstanciaPorTransformacao(produtoVM));

            produtoVM.Nome      = string.Empty;
            produtoVM.Valor     = 999.43M;
            produtoVM.Descricao = string.Empty;

            HttpContent dataRequest = CriarFormDataRequest(produtoVM, imageStream);

            // Act
            HttpResponseMessage response = await base.Client.PutAsync($"{CommonUri}/atualizar-produto-imagem/{produtoVM.Id}", dataRequest);

            // Assert
            var result = await ContentHelper.ExtractObject <ResponseViewModel>(response.Content);

            Assert.False(response.IsSuccessStatusCode);
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.NotEmpty(result.Errors);

            // Clean up
            await DeletarImagemProduto(produtoVM.Id);

            await imageStream.DisposeAsync();

            dataRequest.Dispose();
        }
        public async Task Atualizar_Produto_Com_Imagem_Grande_Com_Erro_Por_Id_Rota_Diferente()
        {
            // Arrange
            FornecedorViewModel fornecedorVM = FornecedorViewModelTestsHelper.ObterInstancia(2, "40405549000180");

            (ProdutoImagemViewModel produtoVM, Stream imageStream) = ProdutoViewModelTestsHelper.ObterInstanciaParaImagemGrande(fornecedorVM);
            Guid rotaId = Guid.NewGuid();

            HttpContent dataRequest = CriarFormDataRequest(produtoVM, imageStream);

            // Act
            HttpResponseMessage response = await base.Client.PutAsync($"{CommonUri}/atualizar-produto-imagem/{rotaId}", dataRequest);

            // Assert
            var result = await ContentHelper.ExtractObject <ResponseViewModel>(response.Content);

            Assert.False(response.IsSuccessStatusCode);
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.Contains("O ID informado não é o mesmo que foi passado na rota!", result.Errors);

            // Clean up
            await DeletarImagemProduto(produtoVM.Id);

            await imageStream.DisposeAsync();

            dataRequest.Dispose();
        }
        public async Task Atualizar_Produto_Com_Imagem_Grande_Com_Sucesso()
        {
            // Arrange
            FornecedorViewModel fornecedorVM = FornecedorViewModelTestsHelper.ObterInstancia(2, "40405549000180");

            (ProdutoImagemViewModel produtoVM, Stream imageStream) = ProdutoViewModelTestsHelper.ObterInstanciaParaImagemGrande(fornecedorVM, $"{base.Factory.Env.WebRootPath}/img");

            await AdicionarObjsParaTestes(fornecedorVM, ProdutoViewModelTestsHelper.ObterInstanciaPorTransformacao(produtoVM));

            produtoVM.Nome      = "Produto de teste com atualização para imagem grande";
            produtoVM.Valor     = 999.43M;
            produtoVM.Descricao = "É o produto teste não um lorem para imagem grande!";
            produtoVM.Ativo     = false;

            HttpContent dataRequest = CriarFormDataRequest(produtoVM, imageStream);

            // Act
            HttpResponseMessage response = await base.Client.PutAsync($"{CommonUri}/atualizar-produto-imagem/{produtoVM.Id}", dataRequest);

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            // Clean up
            await DeletarImagemProduto(produtoVM.Id);

            await imageStream.DisposeAsync();

            dataRequest.Dispose();
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TData"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="httpMethod"></param>
        /// <param name="urlParameters"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public virtual TResult Send <TResult, TData>(string url, TData data = default(TData), IDictionary <string, string> urlParameters = null, HttpMethod httpMethod = null, int?timeout = null)
            where TResult : class
            where TData : class
        {
            var    client     = _httpClient;
            string requestUrl = _baseUrl + url;

            CreateUrlParams(urlParameters, ref requestUrl);
            HttpContent content = null;

            using (HttpRequestMessage request = new HttpRequestMessage())
            {
                request.Method = httpMethod;
                if (data != null)
                {
                    content = CreateContent(data);

                    request.Content = content;
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);
                }
                request.RequestUri = new Uri(requestUrl);
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    TResult result = GetResultAsync <TResult>(response).Result;

                    if (content != null)
                    {
                        content.Dispose();
                    }
                    return(result as TResult);
                }
            }
        }
Example #10
0
 protected override void Dispose(bool disposing)
 {
     if (originalContent != null)
     {
         originalContent.Dispose();
     }
     base.Dispose(disposing);
 }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _returnContent.Dispose();
         _responseMessage?.Dispose();
     }
 }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         content.Dispose();
     }
     base.Dispose(disposing);
 }
Example #13
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _originalContent?.Dispose();
            }

            base.Dispose(disposing);
        }
Example #14
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _inner.Dispose();
            }

            base.Dispose(disposing);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _content.Dispose();
                _progressChanged = null;
            }

            base.Dispose(disposing);
        }
                protected override void Dispose(bool disposing)
                {
                    if (disposing)
                    {
                        // This is important. Disposing original response content will cancel the gRPC call.
                        _inner.Dispose();
                        _innerStream?.Dispose();
                    }

                    base.Dispose(disposing);
                }
Example #17
0
        private async static void HandleResponseContent(HttpResponseMessage response, Func <String, String> onResult)
        {
            HttpContent rawContent = response.Content;
            String      content    = await rawContent.ReadAsStringAsync();

            if (onResult != null)
            {
                onResult(content);
            }
            rawContent.Dispose();
        }
Example #18
0
 private bool m_disposedValue; // Dient zur Erkennung redundanter Aufrufe.
 protected virtual void Dispose(bool disposing)
 {
     if (!m_disposedValue)
     {
         if (disposing)
         {
             m_orgContent.Dispose();
         }
         m_disposedValue = true;
     }
 }
Example #19
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             _content.Dispose();
         }
         disposedValue = true;
     }
 }
Example #20
0
 /// <summary>
 /// 键值对表单内容
 /// </summary>
 /// <param name="content">原始表单</param>
 /// <param name="disposeContent">是否要释放原始表单</param>
 public UrlEncodedContent(HttpContent content, bool disposeContent = true)
 {
     if (content != null)
     {
         content.CopyToAsync(this.stream);
         if (disposeContent == true)
         {
             content.Dispose();
         }
     }
     this.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
 }
Example #21
0
        public static async Task <string> GetStringAsync(string baseUrl, string requestUrl, CancellationToken ct = default(CancellationToken))
        {
            HttpContent content = await GetContentAsync(baseUrl, requestUrl, ct);

            if (content == null)
            {
                return(null);
            }
            string res = await content.ReadAsStringAsync();

            content.Dispose();
            return(res);
        }
Example #22
0
        /// <summary>
        /// Throws an exception if the <see cref="IsSuccessStatusCode"/> property for the HTTP response is false.
        /// </summary>
        /// <returns>The HTTP response message if the call is successful.</returns>
        /// <exception cref="HttpRequestException">Response status code does not indicate success.</exception>
        public FluentResponse EnsureSuccessStatusCode()
        {
            if (IsSuccessStatusCode)
            {
                return(this);
            }

            HttpContent?.Dispose();

            int statusCode = (int)StatusCode;

            throw new HttpRequestException($"Response status code does not indicate success: {statusCode} ({ReasonPhrase}).");
        }
        private static async Task GoogleSearch(object searchTerm)
        {
            Thread.CurrentThread.IsBackground = false;
            string url = @"https://www.google.com/search?q=" + searchTerm;

            Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
            using (var client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    HttpContent content = response.Content;
                    content.Dispose();
                    Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
                }
            }
        }
Example #24
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (_content != null)
                    {
                        _content.Dispose();
                        _content      = null;
                        ContentLength = null;
                    }
                }
                disposedValue = true;
            }
        }
Example #25
0
        public static async Task <HttpResponseMessage> PatchAsync(string url, HttpContent body, Dictionary <string, string> headers = null)
        {
            using var httpClient = new HttpClient();
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }
            var request = await httpClient.PatchAsync(url, body);

            body.Dispose();
            //request.EnsureSuccessStatusCode();
            return(request);
        }
Example #26
0
        /// <summary>
        /// 添加http内容
        /// </summary>
        /// <param name="content">http内容</param>
        /// <param name="disposeContent">是否要释放原始内容</param>
        /// <returns></returns>
        public async Task AddHttpContentAsync(HttpContent content, bool disposeContent = true)
        {
            if (content == null)
            {
                return;
            }

            var buffer = await content.ReadAsByteArrayAsync().ConfigureAwait(false);

            await this.AddByteArrayAsync(buffer).ConfigureAwait(false);

            if (disposeContent == true)
            {
                content.Dispose();
            }
        }
Example #27
0
        private async Task <string> ContinueExecution(object jsonContent, string apiPath, PostTypes postType)
        {
            var result = string.Empty;

            _httpClient = new HttpClient();
            var    claim       = _httpContextAccessor.HttpContext.User.Claims.First(c => c.Type == ConstantString.AccessToken);
            string accessToken = claim.Value;

            if (!string.IsNullOrEmpty(accessToken))
            {
                _httpClient.DefaultRequestHeaders.Add(ConstantString.AccessToken, accessToken);
            }
            _httpClient.DefaultRequestHeaders.Add(Headers.ClientID, Common.ClientID);
            _httpClient.DefaultRequestHeaders.Add(Headers.SecreteToken, Common.ClientSecretKey);
            _httpClient.BaseAddress = new Uri(apiPath);
            if (PostTypes.GET == postType)
            {
                HttpResponseMessage response = await _httpClient.GetAsync(apiPath);

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    result = response.Content.ReadAsStringAsync().Result;
                    break;
                }
                response.Dispose();
            }
            else
            {
                HttpContent         content  = CreateHttpContent <object>(jsonContent);
                HttpResponseMessage response = await _httpClient.PostAsync(apiPath, content);

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    result = response.Content.ReadAsStringAsync().Result;
                    break;
                }
                content.Dispose();
                response.Dispose();
            }
            return(result);
        }
        public static void CleanUpHttp(HttpClient httpClient, HttpContent httpContent, HttpResponseMessage httpResponseMessage)
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
                httpClient = null;
            }

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

            if (httpResponseMessage != null)
            {
                httpResponseMessage.Dispose();
                httpResponseMessage = null;
            }
        }
Example #29
0
        /// <summary>
        /// Send a DELETE request to the specified Uri as an asynchronous operation.
        /// </summary>
        /// <param name="url">The Uri the request is sent to.</param>
        /// <param name="body">The body content the request is sent to.</param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task <HttpResponseMessage> DeleteAsync(string url, HttpContent body, Dictionary <string, string> headers = null)
        {
            using var httpClient = new HttpClient();
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }
            var message = new HttpRequestMessage(HttpMethod.Delete, url)
            {
                Content = body
            };
            var request = await httpClient.SendAsync(message).ConfigureAwait(false);

            message.Dispose();
            body?.Dispose();
            //request.EnsureSuccessStatusCode();
            return(request);
        }
Example #30
0
        public string DownloadHTTPClient(string strLocalPath)
        {
            Logger.Info("Start downloading " + FileURL + " to " + strLocalPath);
            HttpClient client = null;
            FileStream stream = null;

            try
            {
                using (client = new HttpClient())
                {
                    if (!Directory.Exists(strLocalPath))
                    {
                        Directory.CreateDirectory(strLocalPath);
                        Directory.CreateDirectory(Path.Combine(strLocalPath, "Archive"));
                    }
                    string strLocalFile = Path.Combine(strLocalPath, LocalFileName);

                    Logger.Info("Send HttpRequest");
                    HttpContent content = client.GetAsync(FileURL).Result.Content;
                    Logger.Info("Got HttpResponse content");
                    stream = new FileStream(strLocalFile, FileMode.Create, FileAccess.Write, FileShare.None);
                    content.CopyToAsync(stream);
                    Logger.Info("Put them into Stream.");
                    content.Dispose();
                }
                return(Path.Combine(strLocalPath, LocalFileName));
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                return("Failed");
            }
            finally
            {
                client.Dispose();
                stream.Close();
                Logger.Info("Finish downloading " + LocalFileName);
            }
        }