【问题标题】:Google Translate Api error 414 (Request-URI Too Large) java谷歌翻译 Api 错误 414 (Request-URI Too Large) java
【发布时间】:2013-08-23 13:56:15
【问题描述】:

在 Google Translate Api for Java 的官方文档中,它说我们可以使用 post-method 发送超过 2K 的字符。 https://developers.google.com/translate/v2/using_rest

但是,当我尝试翻译长度超过 2k 的文本时,我收到错误 414(请求 URI 太大)。

StringBuilder sb = new StringBuilder();
HttpURLConnection connection = null;
try {
    URL url = new URL("https://www.googleapis.com/language/translate/v2");
    String urlParameters = "key=" + apiKey + "&source=" + shortLang1 + 
            "&target=" + shortLang2 + "&q=" + URLEncoder.encode(lyrics, "UTF-8");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches (false);
    connection.addRequestProperty("X-HTTP-Method-Override", "GET");
    DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
    wr.writeBytes (urlParameters);
    wr.flush ();
    wr.close ();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    if (connection.getResponseCode() != 200) {
        return null;
    }
    String line;
    while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
    }
    reader.close();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (connection != null) {
        connection.disconnect();
    }
}

更新:我明白了,上面的代码是对的。最后我意识到这个错误不是来自 Google 翻译服务,而是来自我在 Google App Engine 上的代理。

【问题讨论】:

    标签: java post google-translate


    【解决方案1】:

    您链接到的文档是说您使用 POST 方法并且您将参数放入请求正文...而不是请求 URL。

    参考:

    【讨论】:

    • 感谢您的回复,但恐怕我不明白您的意思 - 我在 POST 时将参数放入请求正文。就像这里:javadb.com/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多