public void CopyToAsync_Twice()
        {
            var ms = new MemoryStream();

            ms.WriteByte(4);
            ms.WriteByte(12);
            ms.WriteByte(7);
            ms.Seek(1, SeekOrigin.Begin);

            var sc = new StreamContent(ms);

            var dest = new MemoryStream();
            var task = sc.CopyToAsync(dest);

            Assert.True(task.Wait(3000), "#0");
            Assert.AreEqual(2, dest.Length, "#1");
            dest.Seek(0, SeekOrigin.Begin);
            Assert.AreEqual(12, dest.ReadByte(), "#2");

            dest = new MemoryStream();
            task = sc.CopyToAsync(dest);
            Assert.True(task.Wait(3000), "#10");
            Assert.AreEqual(2, dest.Length, "#11");
            dest.Seek(0, SeekOrigin.Begin);
            Assert.AreEqual(12, dest.ReadByte(), "#12");
        }
Example #2
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeeking_ContentIsSerializedMultipleTimes()
        {
            var source  = new MockStream(new byte[10], true, true); // Supports seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);

            Assert.Equal(source.Length, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);

            Assert.Equal(source.Length, destination2.Length);
        }
        public async Task DonationController_AddGivenImage_SuccessfullyAsync()
        {
            //Arrange
            var login = await GetLoginUserAsync(2);

            var given = listGivens[0];

            using (var sc = new StreamContent(File.OpenRead("Img/analgesico.jpg")))
                using (var ms = new MemoryStream())
                {
                    await sc.CopyToAsync(ms);

                    given.Img = ms.ToArray();
                }

            //Act
            using (var postContent = new StringContent(JsonConvert.SerializeObject(given), Encoding.UTF8, "application/json"))
                using (var response = await Environment.ServerApiDonate
                                      .CreateRequest("Donation/AddGivenImageAsync")
                                      .AddHeader("Authorization", "Bearer " + login.access_token)
                                      .And(request => request.Content = postContent)
                                      .And(request => request.Method = HttpMethod.Post)
                                      .PostAsync())
                {
                    //Assert
                    response.EnsureSuccessStatusCode();
                }
        }
Example #4
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeeking_ThrowsInvalidOperationException()
        {
            var source  = new MockStream(new byte[10], false, true); // doesn't support seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);

            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10, destination1.Length);

            // Note that the InvalidOperationException is thrown in CopyToAsync(). It is not thrown inside the task.
            var destination2 = new MemoryStream();

            Assert.Throws <InvalidOperationException>(() => { Task t = content.CopyToAsync(destination2); });
        }
        private static async Task <HttpContent> CreateBufferedRequestContentAsync(
            IOwinRequest owinRequest,
            CancellationToken cancellationToken
            )
        {
            // We need to replace the request body with a buffered stream so that other components can read the stream.
            // For this stream to be useful, it must NOT be diposed along with the request. Streams created by
            // StreamContent do get disposed along with the request, so use MemoryStream to buffer separately.
            MemoryStream buffer;
            int?         contentLength = owinRequest.GetContentLength();

            if (!contentLength.HasValue)
            {
                buffer = new MemoryStream();
            }
            else
            {
                buffer = new MemoryStream(contentLength.Value);
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (StreamContent copier = new StreamContent(owinRequest.Body))
            {
                await copier.CopyToAsync(buffer);
            }

            // Provide the non-disposing, buffered stream to later OWIN components (set to the stream's beginning).
            buffer.Position  = 0;
            owinRequest.Body = buffer;

            // For MemoryStream, Length is guaranteed to be an int.
            return(new ByteArrayContent(buffer.GetBuffer(), 0, (int)buffer.Length));
        }
Example #6
0
        public void CopyToAsync_NullDestination_ThrowsArgumentnullException()
        {
            var source  = new MockStream(new byte[10]);
            var content = new StreamContent(source);

            Assert.Throws <ArgumentNullException>(() => { Task t = content.CopyToAsync(null); });
        }
Example #7
0
        private async Task AddPersonFace(int idPerson)
        {
            foreach (string personFaceFilePath in Directory.EnumerateFiles(
                         $"Img/Faces/{idPerson}", "*", SearchOption.AllDirectories)
                     )
            {
                using (var sc = new StreamContent(File.OpenRead(personFaceFilePath)))
                    using (var ms = new MemoryStream())
                    {
                        await sc.CopyToAsync(ms);

                        var faceViewModel = new FaceViewModel()
                        {
                            IdPersons = idPerson,
                            Image     = ms.ToArray()
                        };

                        using (var postContent = new StringContent(JsonConvert.SerializeObject(faceViewModel), Encoding.UTF8, "application/json"))
                            using (var response = await Environment.ServerApiSecurity
                                                  .CreateRequest("Person/AddPersonFaceAsync")
                                                  .AddHeader("Authorization", "Bearer " + _login.access_token)
                                                  .And(request => request.Content = postContent)
                                                  .And(request => request.Method = HttpMethod.Post)
                                                  .PostAsync())
                            {
                                response.EnsureSuccessStatusCode();
                            }
                    }
            }
        }
Example #8
0
        public void CopyToAsync_Invalid()
        {
            var m = new MemoryStream();

            var sc = new StreamContent(new MemoryStream());

            try {
                sc.CopyToAsync(null);
                Assert.Fail("#1");
            } catch (ArgumentNullException) {
            }

            //
            // For some reason does not work on .net
            //

            /*
             * sc = new StreamContent (new ExceptionStream ());
             * try {
             *  sc.CopyToAsync (m).Wait ();
             *  Assert.Fail ("#2");
             * } catch (AggregateException) {
             * }
             */
        }
Example #9
0
        public void CopyToAsync()
        {
            var ms = new MemoryStream();

            ms.WriteByte(4);
            ms.WriteByte(2);
            ms.Seek(0, SeekOrigin.Begin);

            var sc = new StreamContent(ms);

            var dest = new MemoryStream();
            var task = sc.CopyToAsync(dest);

            task.Wait();
            Assert.AreEqual(2, dest.Length, "#1");

            bool hit = false;

            dest = new MemoryStream();
            var scm = new StreamContentMock(new ExceptionStream());

            scm.OnSerializeToStreamAsync = () => { hit = true; };
            task = scm.CopyToAsync(dest);
            try {
                task.Wait();
                Assert.Fail("#9");
            } catch (AggregateException) {
            }

            Assert.IsTrue(hit, "#10");
        }
        public async Task ImageProcessController_AddByVideoCameraAsync_Successfully()
        {
            //Arrange
            var imageProcess = new ImageProcessViewModel()
            {
                IdVideoCameras = 1,
                IdReference    = Guid.NewGuid(),
                ImageName      = "out000090.png",
                IpUserRequest  = "200.111.222.33",
                VideoPath      = "/user/danieldangeloresendebarros/opt",
                SecondsToStart = 15,
                DtProcess      = DateTime.Now
            };

            using (var sc = new StreamContent(File.OpenRead($"Img/Thumbnail/{imageProcess.ImageName}")))
                using (var ms = new MemoryStream())
                {
                    await sc.CopyToAsync(ms);

                    imageProcess.ImageFile = ms.ToArray();
                }

            //Act
            using (var postContent = new StringContent(JsonConvert.SerializeObject(imageProcess), Encoding.UTF8, "application/json"))
                using (var response = await Environment.ServerApiSecurity
                                      .CreateRequest("ImageProcess/AddByVideoCameraAsync")
                                      .AddHeader("Authorization", "Bearer " + _loginAdm.access_token)
                                      .And(request => request.Content = postContent)
                                      .And(request => request.Method = HttpMethod.Post)
                                      .PostAsync())
                {
                    //Assert
                    response.EnsureSuccessStatusCode();
                }
        }
Example #11
0
        /// <inheritdoc/>
        public async Task <DataElement> InsertBinaryData(string org, string app, int instanceOwnerId, Guid instanceGuid, string attachmentType, string attachmentName, StreamContent content)
        {
            string developer = AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext);
            Guid   dataId    = Guid.NewGuid();
            long   filesize;
            string pathToSaveTo = $"{_settings.GetTestdataForPartyPath(org, app, developer)}{instanceOwnerId}/{instanceGuid}/data";

            Directory.CreateDirectory(pathToSaveTo);
            string fileToWriteTo = $"{pathToSaveTo}/{dataId}";

            using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.OpenOrCreate))
            {
                await content.CopyToAsync(streamToWriteTo);

                await streamToWriteTo.FlushAsync();

                filesize = streamToWriteTo.Length;
            }

            string testDataForParty = _settings.GetTestdataForPartyPath(org, app, developer);
            string instanceFilePath = $"{testDataForParty}{instanceOwnerId}/{instanceGuid}/{instanceGuid}.json";
            FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();

            provider.TryGetContentType(attachmentName, out string contentType);

            lock (Guard(instanceGuid))
            {
                string instanceData = File.ReadAllText(instanceFilePath);

                Instance instance = JsonConvert.DeserializeObject <Instance>(instanceData);

                DataElement data = new DataElement
                {
                    Id                  = dataId.ToString(),
                    ElementType         = attachmentType,
                    ContentType         = contentType,
                    FileName            = attachmentName,
                    StorageUrl          = $"{app}/{instanceGuid}/data/{dataId}",
                    CreatedBy           = instanceOwnerId.ToString(),
                    CreatedDateTime     = DateTime.UtcNow,
                    LastChangedBy       = instanceOwnerId.ToString(),
                    LastChangedDateTime = DateTime.UtcNow,
                    FileSize            = filesize
                };

                if (instance.Data == null)
                {
                    instance.Data = new List <DataElement>();
                }

                instance.Data.Add(data);

                string instanceDataAsString = JsonConvert.SerializeObject(instance);

                File.WriteAllText(instanceFilePath, instanceDataAsString);
                return(data);
            }
        }
Example #12
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeekingPartiallyConsumed_ContentIsSerializedMultipleTimesFromInitialPoint()
        {
            int consumed = 4;
            var source   = new MockStream(new byte[10], true, true); // supports seeking.

            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);

            Assert.Equal(source.Length - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);

            Assert.Equal(source.Length - consumed, destination2.Length);
        }
Example #13
0
        public static async Task <DownloadRequest> DownloadAsync <T>(this string url, IActionContext context, object queryString = null, object model = null, bool isMethodGet = true)
        {
            try
            {
                if (queryString != null && !url.EndsWith("?"))
                {
                    url += "?"; //append querystring delmiter
                }
                DownloadRequest download = new DownloadRequest();

                var request    = ToQueryStringInternal(url, queryString).WithStandardHeaders(context);
                var httpMethod = HttpMethod.Get;
                if (!isMethodGet)
                {
                    httpMethod = HttpMethod.Post;
                }
                CapturedJsonContent capturedJsonContent = new CapturedJsonContent(request.Settings.JsonSerializer.Serialize(model));

                HttpResponseMessage httpResponseMessage = await request.SendAsync(httpMethod, isMethodGet == true?null : capturedJsonContent,
                                                                                  new CancellationToken?(), HttpCompletionOption.ResponseHeadersRead);

                HttpContent content = httpResponseMessage.Content;


                if (content.Headers.ContentDisposition != null)
                {
                    download.FileName        = content.Headers.ContentDisposition.FileName.StripQuotes();
                    download.ContentType     = content.Headers.ContentType.MediaType;
                    download.DispositionType = content.Headers.ContentDisposition.DispositionType;
                }


                download.PushStreamFunction = async(stream) =>
                {
                    using (var downloadStream = await httpResponseMessage.Content.ReadAsStreamAsync())
                        using (var reader = new StreamContent(downloadStream))
                            using (stream) //this has to be called in order to signal caller that we have finished
                            {
                                await reader.CopyToAsync(stream);
                            }
                };
                return(download);
            }
            catch (FlurlHttpException ex)
            {
                if (ex.Call?.HttpStatus == HttpStatusCode.BadRequest)
                {
                    var validationResult = ex.GetResponseJson <ValidationResult>();
                    if (validationResult != null)
                    {
                        throw new ValidationException(validationResult);
                    }
                }
                throw;
            }
        }
Example #14
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeekingButBufferedStream_ContentSerializedOnceToBuffer()
        {
            var source  = new MockStream(new byte[10], false, true); // doesn't support seeking.
            var content = new StreamContent(source);

            // After loading the content into a buffer, we should be able to copy the content to a destination stream
            // multiple times, even though the stream doesn't support seeking.
            await content.LoadIntoBufferAsync();

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);

            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable)
            Assert.Equal(10, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);

            Assert.Equal(10, destination2.Length);
        }
Example #15
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var compressedStream = _encoding.Encode(stream);

            return(_original.CopyToAsync(compressedStream).ContinueWith(tsk =>
            {
                if (compressedStream != null)
                {
                    compressedStream.Dispose();
                }
            }));
        }
Example #16
0
        public void CopyToAsync_ClosedInput()
        {
            var stream  = new MemoryStream(new byte[] { 1 });
            var content = new StreamContent(stream);

            Assert.IsTrue(content.LoadIntoBufferAsync().Wait(3000), "#1");
            stream.Close();

            var stream_out = new MemoryStream(10);

            Assert.IsTrue(content.CopyToAsync(stream_out).Wait(3000), "#2");
        }
Example #17
0
        public async Task <IActionResult> Edit(short id, [Bind("Id,Titre,Description,file,Link")] AdInput ad)
        {
            if (id != ad.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    string accessToken = await HttpContext.GetTokenAsync("access_token");

                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    client.BaseAddress = new Uri(Configuration["URLAPI"] + "api/Ads/" + ad.Id);

                    var           imageContent  = new StreamContent(ad.file.OpenReadStream());
                    StreamContent streamContent = new StreamContent(ad.file.OpenReadStream());
                    var           memoryStream  = new MemoryStream();
                    await streamContent.CopyToAsync(memoryStream);

                    var    bytes  = memoryStream.ToArray();
                    string base64 = Convert.ToBase64String(bytes);
                    double d      = base64.Length;

                    AdPost adPost = new AdPost();
                    adPost.Id                 = ad.Id;
                    adPost.Titre              = ad.Titre;
                    adPost.Description        = ad.Description;
                    adPost.file               = base64;
                    adPost.fileName           = ad.file.FileName;
                    adPost.name               = ad.file.Name;
                    adPost.ContentDisposition = ad.file.ContentDisposition;
                    adPost.ContentType        = ad.file.ContentType;
                    adPost.Link               = ad.Link;

                    string json = await Task.Run(() => JsonConvert.SerializeObject(adPost));

                    var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                    await client.PutAsync(client.BaseAddress, httpContent);
                }
                catch (DbUpdateConcurrencyException)
                {
                    return(NotFound());
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(ad));
        }
        public override async Task ExecuteResultAsync(IWebDavResponse response, CancellationToken ct)
        {
            await base.ExecuteResultAsync(response, ct).ConfigureAwait(false);

            if (_document.FileSystem.SupportsRangedRead)
            {
                response.Headers["Accept-Ranges"] = new[] { "bytes" }
            }
            ;

            var properties = await _document.GetProperties(response.Dispatcher).ToList(ct).ConfigureAwait(false);

            var etagProperty = properties.OfType <GetETagProperty>().FirstOrDefault();

            if (etagProperty != null)
            {
                var propValue = await etagProperty.GetValueAsync(ct).ConfigureAwait(false);

                response.Headers["ETag"] = new[] { propValue.ToString() };
            }

            if (!_returnFile)
            {
                var lastModifiedProp = properties.OfType <LastModifiedProperty>().FirstOrDefault();
                if (lastModifiedProp != null)
                {
                    var propValue = await lastModifiedProp.GetValueAsync(ct).ConfigureAwait(false);

                    response.Headers["Last-Modified"] = new[] { propValue.ToString("R") };
                }

                return;
            }

            using (var stream = await _document.OpenReadAsync(ct).ConfigureAwait(false))
            {
                var content = new StreamContent(stream);
                await SetPropertiesToContentHeaderAsync(content, properties, ct).ConfigureAwait(false);

                foreach (var header in content.Headers)
                {
                    response.Headers.Add(header.Key, header.Value.ToArray());
                }

                await content.CopyToAsync(response.Body).ConfigureAwait(false);
            }
        }
Example #19
0
        public static StreamContent CloneStreamContent(StreamContent content)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                using (System.Threading.Tasks.Task task = content.CopyToAsync(ms))
                {
                    task.Wait();
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(new StreamContent(ms));
            }
            catch { }

            return(content);
        }
Example #20
0
        public async Task <IHttpActionResult> AltUploadAsync()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }

            MultipartMemoryStreamProvider provider = await Request.Content.ReadAsMultipartAsync();

            if (provider.Contents.Count != 1)
            {
                return(BadRequest("Request should contain exactly one pieces of content."));
            }

            StreamContent fileContent = provider.Contents[0] as StreamContent;
            var           headers     = fileContent.Headers;

            var fileName = headers.ContentDisposition.FileNameStar;

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = headers.ContentDisposition.FileName;
                fileName = fileName.TrimStart('\"');
                fileName = fileName.TrimEnd('\"');
            }

            string fullFileName = Directory + fileName;

            using (FileStream fs = new FileStream(fullFileName, FileMode.Create))
            {
                await fileContent.CopyToAsync(fs);

                await fs.FlushAsync();

                Console.WriteLine("Successfully saved file: {0}", fullFileName);
            }

            Process.Start("explorer.exe", Path.GetDirectoryName(fullFileName));

            var text = File.ReadAllText(fullFileName);

            return(CreatedAtRoute(Route_Download, new { file = fileName }, text));
        }
Example #21
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeekingPartiallyConsumed_ContentIsSerializedMultipleTimesFromInitialPoint()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], true, true); // supports seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            Assert.Equal(source.Length - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(source.Length - consumed, destination2.Length);
        }
Example #22
0
        /*
         * 发送POST请求
         */
        public static async Task <string> sendAsrPost(byte[] audioData, String audioFormat, int sampleRate, String url, String ak_id, String ak_secret)
        {
            String result  = "";
            Uri    realUrl = new Uri(url);

            /*
             * http header 参数
             */
            String method       = "POST";
            String accept       = "application/json";
            String content_type = "audio/" + audioFormat;// + ";samplerate=" + sampleRate;
            int    length       = audioData.Length;

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //注册GBK编码
            Encoding encodingGbk = Encoding.GetEncoding("GBK");

            DateTime time = DateTime.UtcNow;
            String   date = ToGMTString(time);
            // 1.对body做MD5+BASE64加密
            String bodyMd5      = MD5Base64(audioData);
            String md52         = MD5Base64(encodingGbk.GetBytes(bodyMd5));
            String stringToSign = method + "\n" + accept + "\n" + md52 + "\n" + content_type + "\n" + date;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;

            using (var handler = new HttpClientHandler())
            {
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Add("Method", method);
                    client.DefaultRequestHeaders.Add("Accept", accept);
                    client.DefaultRequestHeaders.Add("ContentType", content_type);
                    client.DefaultRequestHeaders.Add("ContentLength", audioData.Length.ToString());
                    client.DefaultRequestHeaders.Add("Authorization", authHeader);
                    client.DefaultRequestHeaders.Date = time;

                    using (Stream sr = new MemoryStream())
                    {
                        HttpContent httpContent = new StreamContent(sr);
                        httpContent.Headers.ContentType   = new System.Net.Http.Headers.MediaTypeHeaderValue(content_type);
                        httpContent.Headers.ContentLength = audioData.Length;

                        sr.Write(audioData, 0, audioData.Length);
                        await httpContent.CopyToAsync(sr);

                        sr.Seek(0, SeekOrigin.Begin);
                        await sr.FlushAsync();

                        var httpResponseMessage = client.PostAsync(realUrl, httpContent).Result;
                        var contentType         = httpResponseMessage.Content.Headers.ContentType.CharSet = "utf-8";
                        if (httpResponseMessage.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                        {
                            result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                        }
                    }
                    client.Dispose();
                }
            }
            return(result);
        }
Example #23
0
        /*
         * 发送POST请求
         */
        public static async Task <string> sendTtsPost(String textData, String audioType, String audioName, String url, String ak_id, String ak_secret)
        {
            String result = "";

            Uri realUrl = new Uri(url);

            /*
             * http header 参数
             */
            String method       = "POST";
            String content_type = "text/plain";
            String accept       = "audio/" + audioType;// + ",application/json";
            int    length       = textData.Length;

            DateTime time = DateTime.UtcNow;
            string   date = ToGMTString(time);

            // 1.对body做MD5+BASE64加密
            String bodyMd5      = MD5Base64(Encoding.UTF8.GetBytes(textData));
            String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;

            using (var handler = new HttpClientHandler())
            {
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Add("Method", method);
                    client.DefaultRequestHeaders.Add("Accept", accept);
                    client.DefaultRequestHeaders.Add("ContentType", content_type);
                    client.DefaultRequestHeaders.Add("ContentLength", Encoding.UTF8.GetBytes(textData).Length.ToString());
                    client.DefaultRequestHeaders.Add("Authorization", authHeader);
                    client.DefaultRequestHeaders.Date = time;

                    using (Stream sr = new MemoryStream())
                    {
                        HttpContent httpContent = new StreamContent(sr);
                        httpContent.Headers.ContentType   = new System.Net.Http.Headers.MediaTypeHeaderValue(content_type);
                        httpContent.Headers.ContentLength = Encoding.UTF8.GetBytes(textData).Length;

                        sr.Write(Encoding.UTF8.GetBytes(textData), 0, Encoding.UTF8.GetBytes(textData).Length);
                        await httpContent.CopyToAsync(sr);

                        sr.Seek(0, SeekOrigin.Begin);
                        await sr.FlushAsync();

                        var httpResponseMessage = client.PostAsync(realUrl, httpContent).Result;
                        var contentType         = httpResponseMessage.Content.Headers.ContentType.CharSet = "utf-16";
                        if (httpResponseMessage.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                        {
                            string responseBody = httpResponseMessage.Content.ReadAsStringAsync().Result;
                            if (null != responseBody && 0 < responseBody.Length)
                            {
                                result = ApplicationData.Current.LocalFolder.Path + "/" + audioName + "." + audioType;    //本地保存路径
                                using (FileStream fs = new FileStream(result, FileMode.Append))
                                {
                                    var buff = Encoding.Unicode.GetBytes(responseBody);
                                    fs.Write(buff, 0, buff.Length);
                                }
                            }
                        }
                    }
                    client.Dispose();
                }
            }
            return(result);
        }
Example #24
0
        /*
         * 发送POST请求
         */
        public static async void sendTtsPost(String textData, String audioType, String audioName, String url, String ak_id, String ak_secret)
        {
            HttpResponse response = new HttpResponse();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //注册GBK编码
            Encoding encodingGbk = Encoding.GetEncoding("GBK");

            Encoding encodingUtf8 = Encoding.UTF8;

            Encoding encodingUtf16 = Encoding.Unicode;

            try
            {
                Uri realUrl = new Uri(url);

                /*
                 * http header 参数
                 */
                String method       = "POST";
                String content_type = "text/plain";
                String accept       = "audio/" + audioType;// + ",application/json";

                DateTime time = DateTime.UtcNow;
                string   date = ToGMTString(time);

                // 1.对body做MD5+BASE64加密
                String bodyMd5      = MD5Base64(encodingUtf8.GetBytes(textData));
                String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date;
                // 2.计算 HMAC-SHA1
                String signature = HMACSha1(stringToSign, ak_secret);
                // 3.得到 authorization header
                String authHeader  = "Dataplus " + ak_id + ":" + signature;
                String authHeaders = ak_id + ":" + signature;


                // Create a New HttpClient object.
                using (var handler = new HttpClientHandler())
                {
                    handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                    using (var client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.Add("Method", method);
                        client.DefaultRequestHeaders.Add("Accept", accept);
                        client.DefaultRequestHeaders.Add("ContentType", content_type);
                        client.DefaultRequestHeaders.Add("ContentLength", encodingUtf8.GetBytes(textData).Length.ToString());
                        client.DefaultRequestHeaders.Add("Authorization", authHeader);
                        client.DefaultRequestHeaders.Date           = time;
                        client.DefaultRequestHeaders.ExpectContinue = true;
                        client.Timeout = new TimeSpan(1, 0, 0);

                        using (Stream sr = new MemoryStream())
                        {
                            HttpContent httpContent = new StreamContent(sr);
                            httpContent.Headers.ContentType   = new System.Net.Http.Headers.MediaTypeHeaderValue(content_type);
                            httpContent.Headers.ContentLength = encodingUtf8.GetBytes(textData).Length;

                            sr.Write(encodingUtf8.GetBytes(textData), 0, encodingUtf8.GetBytes(textData).Length);
                            await httpContent.CopyToAsync(sr);

                            sr.Seek(0, SeekOrigin.Begin);
                            await sr.FlushAsync();

                            var httpResponseMessage = await client.PostAsync(realUrl, httpContent);

                            if (httpResponseMessage.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                            {
                                string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();

                                LogTest.LogWrite("responseBody:  ");
                            }
                        }

                        client.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                int a = 0;
            }
        }
Example #25
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeeking_ThrowsInvalidOperationException()
        {
            var source = new MockStream(new byte[10], false, true); // doesn't support seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10, destination1.Length);

            // Note that the InvalidOperationException is thrown in CopyToAsync(). It is not thrown inside the task.
            var destination2 = new MemoryStream();
            Assert.Throws<InvalidOperationException>(() => { Task t = content.CopyToAsync(destination2); });
        }
Example #26
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeekingButBufferedStreamPartiallyConsumed_ContentSerializedOnceToBuffer()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], false, true); // doesn't support seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            // After loading the content into a buffer, we should be able to copy the content to a destination stream
            // multiple times, even though the stream doesn't support seeking.
            await content.LoadIntoBufferAsync();

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10 - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(10 - consumed, destination2.Length);
        }
Example #27
0
 public void CopyToAsync_NullDestination_ThrowsArgumentnullException()
 {
     var source = new MockStream(new byte[10]);
     var content = new StreamContent(source);
     Assert.Throws<ArgumentNullException>(() => { Task t = content.CopyToAsync(null); });
 }
Example #28
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamSupportingSeeking_ContentIsSerializedMultipleTimes()
        {
            var source = new MockStream(new byte[10], true, true); // Supports seeking.
            var content = new StreamContent(source);

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            Assert.Equal(source.Length, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(source.Length, destination2.Length);
        }