无法使用 Yandex Translate API 为 Android studio 中的 Android 应用翻译文本

问题描述 投票:0回答:0

课程代码:


    @Override
    protected String doInBackground(Void... voids) {
        String result = "";
        try {
            URL url = new URL("https://translate.api.cloud.yandex.net/translate/v2/translate");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Bearer " + iamToken);
            conn.setRequestProperty("Content-Type", "application/json");

            String body = String.format("{\"targetLanguageCode\":\"%s\",\"texts\":\"%s\",\"folderId\":\"%s\"}", lang, text, folderId);
            byte[] input = body.getBytes("utf-8");
            OutputStream os = conn.getOutputStream();
            os.write(input, 0, input.length);

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }
            reader.close();
            String response = responseBuilder.toString();

            JSONObject jsonResponse = new JSONObject(response);
            JSONArray translationsArray = jsonResponse.getJSONArray("translations");
            JSONObject translationObj = translationsArray.getJSONObject(0);
            result = translationObj.getString("text");
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("translated",result);
    }
}

尝试停在这条线上:

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

带有以下信息:

java.io.FileNotFoundException: https://translate.api.cloud.yandex.net/translate/v2/translate

我不明白怎么了,代码在 Intellij IDEA 中运行但拒绝在 Android Studio 中运行

我很乐意接受任何建议!

java android-studio httpurlconnection yandex-api
© www.soinside.com 2019 - 2024. All rights reserved.