Beispiel #1
0
        /*
         * 发送POST请求
         */
        public static async void sendAsrPost(byte[] audioData, String audioFormat, int sampleRate, String url, String ak_id, String ak_secret)
        {
            String       result   = "";
            HttpResponse response = new HttpResponse();

            try
            {
                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;

                DateTime time = DateTime.UtcNow;
                String   date = ToGMTString(time);
                // 1.对body做MD5+BASE64加密
                String bodyMd5      = MD5Base64(audioData);
                String md52         = MD5Base64(Encoding.GetEncoding("GBK").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;

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                //注册GBK编码
                Encoding encodingUtf8 = Encoding.UTF8;

                //var httpWebRequest = (HttpWebRequest)WebRequest.Create(realUrl);
                //httpWebRequest.Method = method;
                //httpWebRequest.Accept = accept;
                //httpWebRequest.ContentType = content_type;
                //MethodInfo priLengthMethod = httpWebRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
                //priLengthMethod.Invoke(httpWebRequest.Headers, new[] { "ContentLength", audioData.Length.ToString() });

                //MethodInfo priMethod = httpWebRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
                //priMethod.Invoke(httpWebRequest.Headers, new[] { "Date", date });

                //MethodInfo priAuthorizationMethod = httpWebRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
                //priAuthorizationMethod.Invoke(httpWebRequest.Headers, new[] { "Authorization", authHeader });

                //httpWebRequest.GetRequestStream().Write(audioData, 0, audioData.Length);

                //HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                //if (HttpStatusCode.OK == httpWebResponse.StatusCode)
                //{
                //    response.setStatus(200);
                //    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                //    string responseContent = streamReader.ReadToEnd();
                //    streamReader.Close();
                //    httpWebResponse.Close();
                //    response.setResult(responseContent);
                //    response.setMassage("OK");

                //    string savePath = @"D:\1.Txt";    //本地保存路径

                //    FileStream fs = new FileStream(savePath, FileMode.Append);
                //    var buff = Encoding.Unicode.GetBytes(responseContent);
                //    fs.Write(buff, 0, buff.Length);

                //    fs.Close();
                //}

                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", audioData.Length.ToString());
                        client.DefaultRequestHeaders.Add("Authorization", authHeader);
                        client.DefaultRequestHeaders.Date           = time;
                        client.DefaultRequestHeaders.ExpectContinue = true;
                        //client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
                        client.Timeout = new TimeSpan(1, 0, 0);

                        //using (Stream sr = new MemoryStream())
                        {
                            Stream file = KnownFolders.VideosLibrary.OpenStreamForReadAsync("1.wav").Result;

                            HttpContent httpContent = new StreamContent(file);
                            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();

                            //using (HttpContent httpContent = new ByteArrayContent(encodingUtf8.GetBytes(textData)))
                            {
                                var httpResponseMessage = await client.PostAsync(realUrl, httpContent);

                                if (httpResponseMessage.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                                {
                                    byte[] responseBody = await httpResponseMessage.Content.ReadAsByteArrayAsync();

                                    //using (Stream responseBodys = new MemoryStream())
                                    //{
                                    //    await httpResponseMessage.Content.CopyToAsync(responseBodys);
                                    //    responseBodys.Seek(0, SeekOrigin.Begin);
                                    //    await responseBodys.FlushAsync();
                                    //}


                                    // StreamReader reader = new StreamReader(responseBody);
                                    //string responseResult = reader.ReadToEnd();

                                    //string savePath = ApplicationData.Current.LocalFolder.Path + "/" + audioName + "." + audioType;
                                    //using (FileStream fs = new FileStream(savePath, FileMode.Append))
                                    //{
                                    //    var buff = encodingUtf16.GetBytes(responseResult);
                                    //    fs.Write(buff, 0, buff.Length);
                                    //}
                                    LogTest.LogWrite("responseBody:  "); //+ httpResponseMessage.Content.Headers.ContentLength);
                                }
                            }
                        }

                        client.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                int a = 0;
            }
            //return response;
        }
Beispiel #2
0
        /*
         * 发送POST请求
         */
        public static async void sendTtsPost(String textData, String audioType, String audioName, String url, String ak_id, String ak_secret)
        {
            String       result   = "";
            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";
                string accept = "audio/wav";

                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;

                var baseFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                baseFilter.AllowAutoRedirect         = true;
                baseFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.NoCache;
                using (var client = new HttpClient(baseFilter))
                {
                    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.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Dataplus", authHeaders);
                    client.DefaultRequestHeaders.Date          = time;


                    byte[] bytes = encodingUtf8.GetBytes(textData);
                    InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
                    DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0));
                    datawriter.WriteBytes(bytes);
                    await datawriter.StoreAsync();

                    var httpContent = new HttpStreamContent(memoryStream);
                    httpContent.Headers.ContentType   = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue(content_type);
                    httpContent.Headers.ContentLength = (ulong)encodingUtf8.GetBytes(textData).Length;

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

                    var contentType = httpResponseMessage.Content.Headers.ContentType.CharSet = "utf-16";
                    if (httpResponseMessage.EnsureSuccessStatusCode().StatusCode.ToString().ToLower() == "ok")
                    {
                        StorageFolder folder = await KnownFolders.VideosLibrary.CreateFolderAsync("Greeting", CreationCollisionOption.ReplaceExisting); //创建文件夹

                        StorageFile x = await folder.CreateFileAsync("语音文件.wav", CreationCollisionOption.ReplaceExisting);                              //创建文件

                        StorageFile storageFile = await folder.GetFileAsync("语音文件.wav");

                        string inputStream = await httpResponseMessage.Content.ReadAsStringAsync();

                        byte[] inputBytes = Encoding.Unicode.GetBytes(inputStream);
                        await x.OpenStreamForWriteAsync().Result.WriteAsync(inputBytes, 0, inputBytes.Length);



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

                    client.Dispose();
                }
            }
            catch (Exception e)
            {
                LogTest.LogWrite("错误: " + e.Message);
            }
        }
Beispiel #3
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;
            }
        }