我正在研究一个简单的应用程序"语音文字"通过Google Speech API v2。我创建了一个Java项目并下载了一个flac文件(good-morning-google.flac
)来测试它。
当我将flac文件发送到谷歌服务器时,我收到以下错误:
java.io.IOException:写入服务器时出错。完成时间 sun.net.www.protocol.http.HttpURLConnection.writeRequests(未知 来源)at sun.net.www.protocol.http.HttpURLConnection.writeRequests(未知 来源)at sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知 来自java.net.HttpURLConnection.getResponseCode(未知来源) 在java.net.HttpURLConnection.getResponseMessage(未知来源)at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseMessage(未知 来自)speech.JavaSoundRecorder.main(JavaSoundRecorder.java:140)
我认为问题在于网址的定义,但我不确定。有人可以帮我解决吗?
这是我连接谷歌服务器的代码:
String urlString = "https://www.google.com/speech-api/v2/recognize?output=json&lang=en-US&" + key;
try {
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuilder stringBuilder;
connection.setDefaultUseCaches(true);
connection.setConnectTimeout(20000);
connection.setReadTimeout(60000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac;rate=44100");
/*Write the audio on bufferI/O*/
File file = new File("C:/Travail/audio/good-morning-google.flac");
byte[] buffer = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(buffer);
fis.close();
OutputStream os = connection.getOutputStream();
os.write(buffer);
os.close();
connection.connect();
System.out.println("connect to google server!");
connection.getResponseMessage();
System.out.println("receive the reponse!");
InputStreamReader inputStreamReader = new InputStreamReader(
connection.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
stringBuilder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
System.out.println(stringBuilder);
// JSONObject jsonResponse = new JSONObject(stringBuilder.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
首先使用CURL发布flac文件。
然后,检查来自"连接"的http标头。在java中看到它们与curl相匹配......
如果它们非常接近,那么java帖子也应该有效。
答案 1 :(得分:0)
您在网址定义中的“+ key”之前错过了&key=