使用HttpURLConnection发送二进制数据

4
我想使用Google语音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个回答

4

但是它有getOutputStream(),可以向其中写入数据。您可能还想调用setDoOutput(true)


3
以下代码对我有效。我只是使用了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());

0
使用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();

第二行和第十行的边界是什么意思? - hnnn
3
OP或相应的API文档中是否要求使用multipart表单? - Simon Fischer
@hnnn Boundary是当前时间的十六进制(基于16)表示,以毫秒为单位。根据API,它允许嵌套多部分流的单次处理。请访问http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/MultipartStream.html。 - Udit Saini
请仅返回翻译后的文本:我不确定是否可以在Google API中使用multipart。 - hnnn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接