0

我正在尝试构建一个连接到 Google Voice Search API 的 Java 应用程序。我开发了一个 C# 程序,它运行良好。

C#:

try
{
   FileStream FS_Audiofile = new FileStream("temp.flac", FileMode.Open, FileAccess.Read);
   BinaryReader BR_Audiofile = new BinaryReader(FS_Audiofile);
   byte[] BA_AudioFile = BR_Audiofile.ReadBytes((Int32)FS_Audiofile.Length);
   FS_Audiofile.Close();
   BR_Audiofile.Close();

   HttpWebRequest _HWR_SpeechToText = null;

   _HWR_SpeechToText = (HttpWebRequest)WebRequest.Create("http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=de-DE&maxresults=1&pfilter=0");

   _HWR_SpeechToText.Method = "POST";
   _HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
   _HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
   _HWR_SpeechToText.GetRequestStream().Write(BA_AudioFile, 0, BA_AudioFile.Length);

   HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
   if (HWR_Response.StatusCode == HttpStatusCode.OK)
   {
      StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
   }

}
catch (Exception e)
{

}

这里是代码 Java,它不起作用:

RandomAccessFile accessFile = new RandomAccessFile("temp.flac", "r");
byte[] bs = new byte[(int)accessFile.length()];
accessFile.read(bs);

        try
        {
            HttpURLConnection httpURLConnection = null;
            URL url = new URL("http", "www.google.com", "/speech-api/v1/recognize?xjerr=1&client=chromium&lang=de-DE&maxresults=1&pfilter=0");
            httpURLConnection = (HttpURLConnection)url.openConnection();

            int contentLength = bs.length;

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setInstanceFollowRedirects(false); 
            httpURLConnection.setUseCaches (false);

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "audio/x-flac; rate=44100");
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(contentLength));

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(bs);
            dataOutputStream.flush();

            Scanner scanner = new Scanner(httpURLConnection.getInputStream()).useDelimiter("\\A");
            System.out.println(scanner.toString());

        }
        catch ( Exception e)
        {
           System.out.println(e.toString());
        }

我收到异常“java.io.IOException:写入服务器时出错”。

有谁看到,我在做什么类型的错误?提前感谢您的帮助。

Thx 和问候 Linoge

4

0 回答 0