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

How to send post http request in java for wit.ai audio

我必须使用 http api call.In 将 wave 文件发送到 wit.ai call.In 他们已经使用 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 写入连接输出流的方法,请注意 Bearer 和 [=13] 之间有一个 space =] 固定在以下代码段中:

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: 我已经成功测试了上面的代码,它很有用。