Sunil Kumar Sunil Kumar - 4 years ago 209
HTTP Question

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

I have to send an wave file to wit.ai using http api call.In there documentation they have shown exaple using 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"


I am using java and i have to send this request using java but i am not able to properly convert this curl request in java. i am unable to understand what is -i and -l also how to set data-binary in post request of java.

This what i have done so far

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

Answer Source

Here's how to write the sample.wav to output stream of your connection, beware there's a space between Bearer and token which is fixed in the following snippet:

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: I've successfully tested the code above, it works as a charm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download