2014-09-27 102 views
2

我想使用谷歌语音API,我发现这一切都解释得很好,但即时尝试将其重写到Java。用HttpURLConnection发送二进制数据

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

但它有getOutputStream()你可以写你的数据。您也可以致电setDoOutput(true)

0

使用多部分/混合POST内容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(); 
+0

在第2和第10行究竟代表边界? – hnnn 2014-09-27 20:12:04

+3

OP或相应的API文档在哪里要求多部分? – 2014-09-27 20:16:03

+0

@hnnn边界是以毫秒为单位的当前时间的十六进制(基数为16)表示。根据API,它允许嵌套多部分流的单通处理。访问http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/MultipartStream.html – 2014-09-27 20:32:45

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