使用HttpURLConnection发送二进制数据

时间:2014-09-27 19:27:00

标签: java post google-api httpurlconnection binary-data

我想使用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类没有附加二进制数据的方法。

3 个答案:

答案 0 :(得分:3)

但它有getOutputStream()您可以编写数据。您可能还想致电setDoOutput(true)

答案 1 :(得分:1)

以下代码适合我。我只是使用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());

答案 2 :(得分:0)

对混合POST内容(二进制和字符数据)使用multipart / form-data编码

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