我试图从Java服务使用Bind Speech Rest API,但每次我得到408响应代码。
java.io.IOException:服务器返回HTTP响应代码:408为URL:https://speech.platform.bing.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US
我曾尝试使用不同的方法调用REST API,但始终错误是408请求超时。
虽然我使用类似的调用Speech REST API的代码创建了一个.net示例,但它正在运行。
有没有办法诊断我的Java代码中缺少的内容?
这是我的JAVA代码
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024; // 1024*1024 = 1MB. 212144 is a quarter MB.
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(new File("D://hello.wav"));
URL url = new URL("https://speech.platform.bing.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
conn.setRequestProperty("Transfer-Encoding", "chunked");
conn.setRequestProperty("Accept","application/json;text/xml");
conn.setRequestProperty("Host","speech.platform.bing.com");
//header
conn.setRequestProperty("content-length", String.valueOf(fileInputStream.available()));
conn.setRequestProperty("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000;");
conn.setRequestProperty("Authorization", "Bearer "+ token );
conn.setReadTimeout(22222230);
conn.setDoOutput(true);
conn.connect();
dos = new DataOutputStream(conn.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
try {
dos.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError oome) {
oome.printStackTrace();
fileInputStream.close();
throw new Exception("Out Of Memory!");
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
fileInputStream.close();
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
Bing Speech API需要音频数据的分块传输。但是对于HttpURLConnection
类,设置Transfer-Encoding
标题并不会神奇地导致转换类型切换 - 您需要通过setChunkedStreamingMode
或其中一个变体显式设置流模式。你还想省略Content-Length
标题。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(0);
//header
conn.setRequestProperty("Accept","application/json;text/xml");
conn.setRequestProperty("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000;");
conn.setRequestProperty("Authorization", "Bearer "+ token );