【问题标题】:How to send post http request in java for wit.ai audio如何在java中为wit.ai音频发送post http请求
【发布时间】:2017-02-04 06:36:23
【问题描述】:

我必须使用 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 的 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());
}

【问题讨论】:

  • 你应该对Java网络有一个基本的了解,docs.oracle.com/javase/tutorial/networking/urls/…是一个很好的起点。
  • @jerry Chin 我有,但我很困惑并且收到错误我不是专业人士你能转换这个吗?请帮忙
  • 你能发布错误以及你做了什么吗?

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


【解决方案1】:

以下是如何将sample.wav 写入连接的输出流,注意Bearertoken 之间有一个空格,它在以下 sn-p 中已修复:

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

【讨论】:

  • 感谢您提供急需的帮助。但您能否解释一下 curl 中的 -i 和 -L 是什么?
  • -i 在输出中包含标题; -L 如果请求的页面已移动到新位置,将重做请求。如果需要更多详细信息,您最好查看linux.die.net/man/1/curl
猜你喜欢
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多