2014-09-27 6 views
2

Google 음성 API를 사용하고 싶습니다. 모든 내용이 잘 설명되어 있지만 java로 다시 작성하려고하는이 https://github.com/gillesdemey/google-speech-v2/을 발견했습니다.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 클래스에는 2 진 데이터를 첨부 할 수있는 방법이 없습니다.

답변

3

하지만 데이터를 쓸 수있는 getOutputStream()이 있습니다. setDoOutput(true)으로 전화 할 수도 있습니다.

0

를 사용하여 다중/혼합 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(); 
+0

정확히 2 번째 줄과 10 번째 줄의 경계를 나타내는 것은 무엇입니까? – hnnn

+3

OP 또는 해당 API 문서는 어디에서 여러 부분을 요청 했습니까? –

+0

@hnnn 경계는 현재 시간 (밀리 초)의 16 진수 (16 진수) 표현입니다. API에 따라 중첩 된 여러 부분 스트림의 단일 패스 처리를 허용합니다. http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/MultipartStream.html –

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