谷歌翻译Api错误414(请求URI太大)java



在Google Translate Api for Java的官方文档中,它说我们可以使用post方法发送超过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();
    }
}

更新:我明白了,上面的代码是对的。最后我意识到这个错误不是来自谷歌翻译服务,而是来自我在谷歌应用引擎上的代理。

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

参考:

  • HTTP POST请求中的参数是如何发送的

最新更新