REST-API получает ошибку 403 при инициализации потоков - PullRequest
0 голосов
/ 07 октября 2018

Я начал работать с google speech api, но при инициализации streams я все еще получаю ошибку 403 .Я включил User-Agent в запрос, но, похоже, он все еще дает мне ошибку.

Api key действительно допустим, потому что я получаю ответ при запросе в командной строке или почтальоне.

public static void main(String[] args) {

    String key = "xxxx";
    String urlString = "https://www.google.com/speech-api/v2/recognize?output=json&lang=en-US&key=" + key;
    try {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        StringBuilder stringBuilder;


        connection.setDefaultUseCaches(true);
        connection.setConnectTimeout(100000);
        connection.setReadTimeout(100000);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Authorization", key);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "audio/x-flac;rate=16100");

        File file = new File("C://Users//Łukasz//Downloads//brooklyn.flac");
        byte[] buffer = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(buffer);
        fis.close();
        OutputStream os = connection.getOutputStream();
        os.write(buffer);
        System.out.println(os==null);
        os.close();

        connection.connect();
        System.out.println("connect to google server!");
        connection.getResponseMessage();
        System.out.println("receive the reponse!");

        InputStreamReader inputStreamReader = new InputStreamReader(
                connection.getInputStream(), "UTF-8");
        BufferedReader br = new BufferedReader(inputStreamReader);

        stringBuilder = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        System.out.println(stringBuilder);

    } catch (
            MalformedURLException e) {
        e.printStackTrace();
    } catch (
            IOException e) {
        e.printStackTrace();
    }
}
}
...