用HttpURLConnection发送二进制数据
我想使用谷歌语音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类没有附加二进制数据的方法。
但它有getOutputStream()
,您可以在其中编写数据。 您可能还想调用setDoOutput(true)
。
下面的代码适用于我。 我只是使用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());
对混合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("rn");
writer.append("Content-Disposition: form-data; name="binaryFile"; filename="" + binaryFile.getName() + """).append("rn");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()).append("rn");
writer.append("Content-Transfer-Encoding: binary").append("rn");
writer.append("rn").flush();
链接地址: http://www.djcxy.com/p/41341.html
上一篇: Sending binary data with HttpURLConnection
下一篇: How to receive data from php server by delphi client through HTTP connection?