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

时间:2017-02-04 06:36:24

标签: java web-services http curl wit.ai

我必须使用http api调用将一个wave文件发送到wit.ai。在那里,他们使用curl显示了exaple

$ 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());
}

1 个答案:

答案 0 :(得分:1)

以下是如何将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:我已经成功测试了上面的代码,它可以作为一种魅力。