我正在使用Microsoft认知服务器将其文本转换为语音。
我的讲师为我提供了此Java程序来建立HTTP连接。
每当我运行httpConnect
方法时,都会得到Connection to the Internet has failed. Please try again.
异常。我对代码的了解不多,无法知道为什么会发生这种情况。
据我所知,该服务的密钥都是最新的。
堆栈跟踪:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://speech.platform.bing.com/synthesize
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
at HttpConnect.httpConnect(HttpConnect.java:46)
at SpeechGenerator.generateSpeech(SpeechGenerator.java:49)
at SpeechGenerator.generate(SpeechGenerator.java:89)
at Main.main(Main.java:26)
代码:
public class HttpConnect {
final static int TIMEOUT = 10000; /* ms */
final static int BUFFSIZE = 4096; /* 4KB */
public static byte[] httpConnect(String method, String url, String[][] headers, byte[] body) {
try {
/*
* Setup connection.
*/
URL u = new URL( url );
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod( method );
conn.setDoInput ( true );
conn.setDoOutput( true );
conn.setConnectTimeout( TIMEOUT );
conn.setReadTimeout ( TIMEOUT );
for ( int i = 0; i < headers.length; i++ ) {
conn.setRequestProperty( headers[ i ][ 0 ], headers[ i ][ 1 ] );
}
conn.connect();
/*
* Send data.
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.write( body );
dos.flush();
dos.close();
/*
* Receive data.
*/
DataInputStream dis = new DataInputStream( conn.getInputStream() );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[ BUFFSIZE ];
for (;;) {
int n = dis.read( buffer );
if ( n > 0 ) {
bos.write( buffer, 0, n );
} else {
break;
}
}
byte response[] = bos.toByteArray();
dis.close();
/*
* Teardown connection.
*/
conn.disconnect();
return response;
} catch ( SocketTimeoutException ex ) {
System.out.println( "Connection to the Internet has timed out. Please try again." ); //Edited exception - Josh
return null;
} catch ( Exception ex ) {
System.out.println( "Connection to the Internet has failed. Please try again. " ); //Edited exception - Josh
ex.printStackTrace();
return null;
}
}
}