在Android中阅读Google Translator中的任何语言字符串

时间:2017-07-28 09:56:17

标签: java android string bufferedreader google-translate

我正在创建一个翻译应用程序,我从android支持的语音识别器获取输入文本。示例:印地语,中文等。现在我想构建这样的查询 -

public JSONObject getTranslatedText() {
    StringBuilder sb = new StringBuilder();
    String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
    JSONObject response = null;
    String json = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(http);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        urlConnection.connect();

        String line1 = "{\n" + "  'q': '" + inputString + "',\n" + "  'target': '" + targetcodeString + "'\n" + "}";

        DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
        out.writeBytes(line1);
        out.flush();
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        json = sb.toString();
        response = new JSONObject(json);
    } catch (MalformedURLException e) {

    } catch (IOException e) {

    } catch (JSONException e) {

    } finally {
        if (urlConnection != null) urlConnection.disconnect();

    }
    return response;
}

问题是它没有正确编码,我得到这样的输出 - 示例:对于印地语中的“你好吗”,即“क्याहाल”,如9& HG 08 * E

请帮我解决一下。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用Html.fromHtml(yourTranslatedStr).toString()。 我用印地语试过了,但它确实有效。