Отправка двоичных данных с помощью HttpURLConnection

Я хочу использовать google speech api, я нашел это https://github.com/gillesdemey/google-speech-v2/, где все объясняется хорошо, но и я пытаюсь переписать это в 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");

Теперь я потерял... я думаю, мне нужно добавить bytearray в запрос. в примере его строка

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

но класс httpurlconnection не имеет метода для привязки двоичных данных.

Ответ 1

Но у него есть getOutputStream(), на который вы можете написать свои данные. Вы также можете вызвать setDoOutput(true).

Ответ 2

Код ниже работает для меня. Я просто использовал commons-io для упрощения, но вы можете заменить это:

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

Ответ 3

Использовать кодировку multipart/form-data для смешанного содержимого POST (двоичные и символьные данные)

//set connection property
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + <random-value>);

PrintWriter writer = null;
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);


// Send binary file.
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()).append("\r\n");
writer.append("Content-Transfer-Encoding: binary").append("\r\n");
writer.append("\r\n").flush();