Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending binary data with HttpURLConnection

i want to use google speech api, i've found this https://github.com/gillesdemey/google-speech-v2/ where everything is explained well, but and im trying to rewrite it into java.

File filetosend = new File(path);
byte[] bytearray = Files.readAllBytes(filetosend);
URL url = new URL("https://www.google.com/speech-api/v2/recognize?output="+outputtype+"&lang="+lang+"&key="+key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
//header
conn.setRequestProperty("Content-Type", "audio/x-flac; rate=44100");

now im lost... i guess i need to add the bytearray into the request. in the example its line

--data-binary @audio/good-morning-google.flac \

but httpurlconnection class has no method for attaching binary data.

like image 419
hnnn Avatar asked Feb 12 '23 22:02

hnnn


2 Answers

But it has getOutputStream() to which you can write your data. You may also want to call setDoOutput(true).

like image 190
Simon Fischer Avatar answered Feb 15 '23 10:02

Simon Fischer


The code below works for me. I just used commons-io to simplify, but you can replace that:

    URL url = new URL("https://www.google.com/speech-api/v2/recognize?lang=en-US&output=json&key=" + key);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
    IOUtils.copy(new FileInputStream(flacAudioFile), conn.getOutputStream());
    String res = IOUtils.toString(conn.getInputStream());
like image 24
Italo Borssatto Avatar answered Feb 15 '23 09:02

Italo Borssatto