0

Class code:

    @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);
    }
}

Try stops at the line:

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

With the following message:

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

I don't understand what's wrong, the code worked in IntelliJ IDEA but refuses to work in Android Studio.

I will be glad to any advice!

Halil Ozel
  • 2,482
  • 3
  • 17
  • 32

0 Answers0