如何在java中发送发布http请求以 wit.ai 音频



我必须使用 http api 调用向 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 的后请求中设置数据二进制。

这是我到目前为止所做的

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:我已经成功测试了上面的代码,它作为一个魅力。

最新更新