如何发送POST HTTP请求的Java进行wit.ai音频
问题描述:
我发送波形文件使用HTTP API call.In有文档wit.ai他们表现出的exaple使用curl如何发送POST HTTP请求的Java进行wit.ai音频
$ 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,也不知道如何在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
写信给你连接的输出流,提防有Bearer
和token
之间的空间其固定在下面的代码片段:
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:我已经成功地测试了上面的代码,它作为一个魅力。
+0
非常感谢您的帮助。但是,您仍然可以向我解释卷曲中的-i和-L是什么? –
+0
-i在输出中包含标题;如果所请求的页面已移至新位置,-L将重新执行请求。如果需要更多详细信息,最好查看https://linux.die.net/man/1/curl。 –
您应该对Java网络有基本的了解,https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html是一个很好的起点。 –
@jerry Chin我确实有,但我很困惑,并得到错误,我不亲你能转换吗?请帮助 –
你可以发布错误和你做了什么? –