Java Google Speech API code fails

147 views Asked by At

I am trying to use google speech cloud API version 2 in my java application. Not sure where is the issue, but when i tried the URL and same audio, config settings in PHP it worked and i got the response. Please help.

Code

package testing;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.net.ssl.HttpsURLConnection;

import org.apache.xmlbeans.impl.util.Base64;
import org.json.JSONObject;


public class test
{
 public static void main(String s[]){
 test http = new test();
          System.out.println("\nTesting 2 - Send Http POST request");
          try {
                 http.sendPost();
          } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
          }

   }

   private void sendPost() throws Exception {


          String url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?fields=results&key=<<Google KEY>>";


          URL obj = new URL(url);
          HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

          JSONObject encoding = new JSONObject();
          encoding.put("encoding","LINEAR16");
          encoding.put("sampleRate","8000");
          encoding.put("languageCode","en-IN");

          JSONObject content = new JSONObject();
          content.put("content",Base64.encode(Files.readAllBytes(Paths.get("C:\\speech.wav"))));

          JSONObject data = new JSONObject();
          data.put("audio", content);
          data.put("config", encoding);


          // Send post request
          con.setRequestMethod("POST");
          con.setDoInput(true);
          con.setDoOutput(true);
          con.setUseCaches(false);
          con.setRequestProperty("Content-Type", "application/json");
          con.setRequestProperty("Content-Length", data.toString().length()+"");
         // con.setRequestProperty("User-Agent", "Mozilla/5.0");
          OutputStream os = con.getOutputStream();
          os.write(URLEncoder.encode(data.toString(),"UTF-8").getBytes());
          os.flush();
          System.out.println(data.toString());
          os.close();

          int responseCode = con.getResponseCode();
          System.out.println("\nSending 'POST' request to URL : " + url);
          System.out.println("Response Code : " + responseCode);
          System.out.println("Response msg : " + con.getResponseMessage());
          System.out.println("Response headers : " + con.getHeaderFields());

          BufferedReader in = new BufferedReader(
                  new InputStreamReader(con.getInputStream(),"UTF-8"));
          String inputLine;

          while ((inputLine = in.readLine()) != null) {
              System.out.println(inputLine);
                 //response.append(inputLine);
          }
          in.close();

 }

 }

Response

JSON Data : {"audio":{"content": <<Byte of audio>>},"config":{"sampleRate":"8000","languageCode":"en-IN","encoding":"LINEAR16"}}


 Response Code : 400
 Response msg : Bad Request
Response headers : {null=[HTTP/1.1 400 Bad Request], X-Frame-Options=[SAMEORIGIN], Alt-Svc=[quic=":443"; ma=2592000; v="35,34"], Transfer-Encoding=[chunked], Vary=[Origin,Accept-Encoding, Referer, X-Origin], Date=[Sun, 01 Jan 2017 16:57:07 GMT], X-XSS-Protection=[1; mode=block], Accept-Ranges=[none], Content-Type=[application/json; charset=UTF-8], Server=[ESF], X-Content-Type-Options=[nosniff], Cache-Control=[private]}
  java.io.IOException: Server returned HTTP response code: 400 for URL: 
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
 at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
 at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
 at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1672)
 at java.security.AccessController.doPrivileged(Native Method)
 at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1670)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1243)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at testing.test.sendPost(test.java:75)
at testing.test.main(test.java:23)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at testing.test.sendPost(test.java:68)
... 1 more
1

There are 1 answers

0
林浩廷 On

Please try without URLEncoder just like this -

os.write(data.toString().getBytes("UTF-8"));