gpt4 book ai didi

java - 如何在java中为wit.ai音频发送post http请求

转载 作者:行者123 更新时间:2023-12-01 08:55:57 26 4
gpt4 key购买 nike

我必须使用http api调用将wave文件发送到wit.ai。在文档中他们展示了使用curl的示例

$ curl -XPOST 'https://api.wit.ai/speech?v=20141022' \
-i -L \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: audio/wav" \
--data-binary "@sample.wav"

我正在使用java,我必须使用java发送这个请求,但是我无法在java中正确转换这个curl请求。我无法理解什么是 -i 和 -l 以及如何在 java 的 post 请求中设置数据二进制。

这就是我到目前为止所做的

public static void main(String args[])
{
String url = "https://api.wit.ai/speech";
String key = "token";

String param1 = "20170203";
String param2 = command;
String charset = "UTF-8";

String query = String.format("v=%s",
URLEncoder.encode(param1, charset));


URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty ("Authorization","Bearer"+ key);
connection.setRequestProperty("Content-Type", "audio/wav");
InputStream response = connection.getInputStream();
System.out.println( response.toString());
}

最佳答案

以下是如何编写sample.wav来输出连接流,请注意Bearertoken之间有一个空格 已在以下代码片段中修复:

public static void main(String[] args) throws Exception {
String url = "https://api.wit.ai/speech";
String key = "token";

String param1 = "20170203";
String param2 = "command";
String charset = "UTF-8";

String query = String.format("v=%s",
URLEncoder.encode(param1, charset));


URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty ("Authorization","Bearer " + key);
connection.setRequestProperty("Content-Type", "audio/wav");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
FileChannel fileChannel = new FileInputStream(path to sample.wav).getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

while((fileChannel.read(byteBuffer)) != -1) {
byteBuffer.flip();
byte[] b = new byte[byteBuffer.remaining()];
byteBuffer.get(b);
outputStream.write(b);
byteBuffer.clear();
}

BufferedReader response = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = response.readLine()) != null) {
System.out.println(line);
}
}

PS:我已经成功测试了上面的代码,它很有魅力。

关于java - 如何在java中为wit.ai音频发送post http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42037349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com