ReadAsByteArrayAsync() 공개 메소드

public ReadAsByteArrayAsync ( ) : Task
리턴 Task
예제 #1
1
        /*
         * Responsible for creating a success result of some sort.
         */
        async Task <Response <TOut> > GetSuccessResult <TOut>(
            net.HttpContent content,
            Response <TOut> responseResult)
        {
            if (typeof(TOut) == typeof(byte[]) || typeof(TOut) == typeof(object))
            {
                var contentType = content.Headers.ContentType?.MediaType ?? "application/json";
                switch (contentType)
                {
                case "application/json":
                case "application/hyperlambda":
                    responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();

                    break;

                default:
                    if (contentType.StartsWith("text/"))
                    {
                        responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();
                    }
                    else
                    {
                        responseResult.Content = (TOut)(object)await content.ReadAsByteArrayAsync();
                    }
                    break;
                }
            }
            else if (typeof(TOut) == typeof(string))
            {
                responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();
            }
            else if (typeof(IConvertible).IsAssignableFrom(typeof(TOut)))
            {
                var txtContent = await content.ReadAsStringAsync();

                responseResult.Content = (TOut)Convert.ChangeType(txtContent, typeof(TOut));
            }
            else
            {
                var txtContent = await content.ReadAsStringAsync();

                var objResult = JToken.Parse(txtContent);
                responseResult.Content = objResult.ToObject <TOut>();
            }

            return(responseResult);
        }
예제 #2
0
        private async Task <byte[]> GetByteArrayAsyncCore(Task <HttpResponseMessage> getTask)
        {
            // Wait for the response message.
            using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
            {
                // Make sure it completed successfully.
                responseMessage.EnsureSuccessStatusCode();

                // Get the response content.
                HttpContent c = responseMessage.Content;
                if (c != null)
                {
#if NET46
                    return(await c.ReadAsByteArrayAsync().ConfigureAwait(false));
#else
                    HttpContentHeaders headers = c.Headers;
                    using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
                    {
                        long?  contentLength = headers.ContentLength;
                        Stream buffer; // declared here to share the state machine field across both if/else branches

                        if (contentLength.HasValue)
                        {
                            // If we got a content length, then we assume that it's correct and create a MemoryStream
                            // to which the content will be transferred.  That way, assuming we actually get the exact
                            // amount we were expecting, we can simply return the MemoryStream's underlying buffer.
                            buffer = new HttpContent.LimitMemoryStream(_maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault());
                            await responseStream.CopyToAsync(buffer).ConfigureAwait(false);

                            if (buffer.Length > 0)
                            {
                                return(((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer());
                            }
                        }
                        else
                        {
                            // If we didn't get a content length, then we assume we're going to have to grow
                            // the buffer potentially several times and that it's unlikely the underlying buffer
                            // at the end will be the exact size needed, in which case it's more beneficial to use
                            // ArrayPool buffers and copy out to a new array at the end.
                            buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize);
                            try
                            {
                                await responseStream.CopyToAsync(buffer).ConfigureAwait(false);

                                if (buffer.Length > 0)
                                {
                                    return(((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray());
                                }
                            }
                            finally { buffer.Dispose(); }
                        }
                    }
#endif
                }

                // No content to return.
                return(Array.Empty <byte>());
            }
        }
        private static async Task AssertContentLengthHeaderValueAsync(HttpContent content)
        {
            long contentLength            = (await content.ReadAsByteArrayAsync()).LongLength;
            long contentLengthHeaderValue = content.Headers.ContentLength.GetValueOrDefault();

            Assert.Equal(contentLength, contentLengthHeaderValue);
        }
예제 #4
0
        private static void AssertContentLengthHeaderValue(HttpContent content)
        {
            long contentLength            = content.ReadAsByteArrayAsync().Result.LongLength;
            long contentLengthHeaderValue = content.Headers.ContentLength.GetValueOrDefault();

            Assert.Equal(contentLength, contentLengthHeaderValue);
        }
예제 #5
0
        public virtual void Write(JsonWriter writer, HttpContent content)
        {
            if (content == null)
                return;

            var bytes = content.ReadAsByteArrayAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            IEnumerable<string> contentTypeValues;
            string contentTypeHeaderValue;
            if (content.Headers.TryGetValues("Content-Type", out contentTypeValues))
                contentTypeHeaderValue = contentTypeValues.Last();
            else
                contentTypeHeaderValue = "text/html; charset=utf-8";

            writer.WritePropertyName("format");

            var contentType = new ContentType(contentTypeHeaderValue);
            bool formatAsBinary = false;
            var encoding = Encoding.ASCII;
            if (contentType.CharSet != null)
                encoding = Encoding.GetEncoding(contentType.CharSet);
            else
                formatAsBinary = bytes.Any(c => c == 0 || c > 127);
            if (formatAsBinary)
            {
                writer.WriteValue("binary");
                writer.WritePropertyName("body");
                writer.WriteValue(Convert.ToBase64String(bytes));
            }
            else
            {
                // Need to use memory stream to avoid UTF-8 BOM weirdness
                string str;
                using (var ms = new MemoryStream(bytes))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        str = sr.ReadToEnd();
                    }
                }

                if (contentType.MediaType == "application/json" || contentType.MediaType.EndsWith("+json"))
                {
                    var jtoken = JToken.Parse(str);
                    writer.WriteValue("json");
                    writer.WritePropertyName("body");
                    jtoken.WriteTo(writer);
                }
                else
                {
                    writer.WriteValue("text");
                    writer.WritePropertyName("body");
                    //writer.WriteValue(str);

                    // Represent the text as an array of strings split at \r\n to make long text content easier to read.
                    WriteStringFomat(writer, contentType, str);
                }
            }
        }
예제 #6
0
 public static async Task<byte[]> ComputeHash(HttpContent httpContent)
 {
     using (var md5 = MD5.Create())
     {
         var content = await httpContent.ReadAsByteArrayAsync();
         byte[] hash = md5.ComputeHash(content);
         return hash;
     }
 }
예제 #7
0
        /// <inheritdoc />
        /// <exception cref="System.ArgumentNullException">
        /// The <paramref name="content"/> parameter is <c>null</c>.
        /// </exception>
        protected internal override void SetContent(HttpContent content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            _content = content.ReadAsByteArrayAsync().Result;
        }
예제 #8
0
 public byte[] ComputeHash(HttpContent httpContent)
 {
     using (var md5 = MD5.Create())
     {
         var content = httpContent.ReadAsByteArrayAsync().Result;
         var hash = md5.ComputeHash(content);
         return hash;
     }
 }
        /// <summary>
        /// 读取为二进制数组并转换为指定的编码
        /// </summary>
        /// <param name="httpContent"></param>
        /// <param name="dstEncoding">目标编码</param>
        /// <exception cref="ArgumentException"></exception>
        /// <returns></returns>
        public static async Task <byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, Encoding dstEncoding)
        {
            var encoding  = httpContent.GetEncoding();
            var byteArray = await httpContent.ReadAsByteArrayAsync().ConfigureAwait(false);

            return(encoding.Equals(dstEncoding)
                ? byteArray
                : Encoding.Convert(encoding, dstEncoding, byteArray));
        }
예제 #10
0
        private static string ExtractBody(HttpContent content)
        {
            if (content == null)
            {
                return string.Empty;
            }

            var task = content.ReadAsByteArrayAsync();
            return Encoding.UTF8.GetString(task.Result);
        }
		/// <inheritdoc />
		public async Task<object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (!CanConvertFromHttpContent(resultType, httpContent))
			{
				throw new NotSupportedException("CanConvertFromHttpContent resulted in false, this is not supposed to be called.");
			}
			Log.Debug().WriteLine("Retrieving the content as byte[], Content-Type: {0}", httpContent.Headers.ContentType);

			return await httpContent.ReadAsByteArrayAsync().ConfigureAwait(false);
		}
        public static async Task<string> ComputeContentHashAsync(HttpContent httpContent)
        {
            if (httpContent == null)
                return null;

            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] content = await httpContent.ReadAsByteArrayAsync().ConfigureAwait(false);
                return content.Length != 0
                    ? Convert.ToBase64String(sha256.ComputeHash(content))
                    : null;
            }
        }
 public static async Task<PreventDisposeContentWrapper> CreateWrapperAsync(HttpContent wrappedContent)
 {
     if (wrappedContent == null)
     {
         return new PreventDisposeContentWrapper(new byte[0], null);
     }            
     var bytes = await wrappedContent.ReadAsByteArrayAsync();
     var wrapper = new PreventDisposeContentWrapper(bytes, wrappedContent.GetType());
     foreach (var header in wrappedContent.Headers)
     {
         wrapper.Headers.Add(header.Key, header.Value);
     }
     return wrapper;
 }
        /// <summary>
        /// Decompresses the compressed HTTP content.
        /// </summary>
        /// <param name="compressedContent">The compressed HTTP content.</param>
        /// <param name="compressor">The compressor.</param>
        /// <returns>The decompressed content.</returns>
        public async Task<HttpContent> DecompressContent(HttpContent compressedContent, ICompressor compressor)
        {
            var decompressedContentStream = new MemoryStream();

            // Decompress buffered content
            using (var ms = new MemoryStream(await compressedContent.ReadAsByteArrayAsync()))
            {
                await compressor.Decompress(ms, decompressedContentStream).ConfigureAwait(false);
            }

            // Set position back to 0 so it can be read again
            decompressedContentStream.Position = 0;

            var decompressedContent = new StreamContent(decompressedContentStream);

            // Copy content headers so we know what got sent back
            this.CopyHeaders(compressedContent, decompressedContent);

            return decompressedContent;
        }
예제 #15
0
 /// <summary>
 /// Creates an array copy of the <paramref name="content"/> without affecting the <see cref="Stream.Position"/> of the original object.
 /// </summary>
 private static async Task<byte[]> CloneArrayAsync(HttpContent content)
 {
     var result = await content.ReadAsByteArrayAsync();
     var stream = await content.ReadAsStreamAsync();
     if (stream.CanSeek) stream.Position = 0;
     return result;
 }
 /// <summary>
 ///     Serialize the HTTP content to a byte array as a synchronous operation.
 /// </summary>
 public static byte[] ReadAsByteArray(this HttpContent content)
 {
     return(Task.Run(() => content.ReadAsByteArrayAsync()).Result);
 }
 /// <summary>
 /// 读取为二进制数组并转换为utf8编码
 /// </summary>
 /// <param name="httpContent"></param>
 /// <exception cref="ArgumentException"></exception>
 /// <returns></returns>
 public static Task <byte[]> ReadAsUtf8ByteArrayAsync(this HttpContent httpContent)
 {
     return(httpContent.ReadAsByteArrayAsync(Encoding.UTF8));
 }
        internal static HttpContent CreateBufferedCopyOfContent(HttpContent content)
        {
            if (content != null)
            {
                SharedByteArrayContent shareableContent = content as SharedByteArrayContent;
                byte[] contentBytes = shareableContent == null ?
                    content.ReadAsByteArrayAsync().Result :
                    shareableContent.ContentBytes;

                HttpContent bufferedContent = new SharedByteArrayContent(contentBytes);

                foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
                {
                    bufferedContent.Headers.AddHeaderWithoutValidation(header);
                }

                return bufferedContent;
            }

            return null;
        }
 private static void AssertContentLengthHeaderValue(HttpContent content)
 {
     long contentLength = content.ReadAsByteArrayAsync().Result.LongLength;
     long contentLengthHeaderValue = content.Headers.ContentLength.GetValueOrDefault();
     Assert.Equal(contentLength, contentLengthHeaderValue);
 }
 private static async Task<byte[]> ComputeHash(HttpContent httpContent)
 {
     using (MD5 md5 = MD5.Create())
     {
         byte[] hash = null;
         var content = await httpContent.ReadAsByteArrayAsync();
         if (content.Length != 0)
         {
             hash = md5.ComputeHash(content);
         }
         return hash;
     }
 }
 /// <summary>
 ///     Serialize the HTTP content to a string as a synchronous operation.
 /// </summary>
 public static string ReadAsString(this HttpContent content, Encoding encoding)
 {
     return(encoding.GetString(Task.Run(() => content.ReadAsByteArrayAsync()).Result));
 }
        /// <summary>
        ///     Serialize the HTTP content to a string as an asynchronous operation.
        /// </summary>
        public async static Task <string> ReadAsStringAsync(this HttpContent content, Encoding encoding)
        {
            var bytes = await content.ReadAsByteArrayAsync();

            return(encoding.GetString(bytes));
        }