1
在Google翻譯的Api for Java官方文檔中,它表示我們可以使用post-method發送超過2K個字符。 https://developers.google.com/translate/v2/using_rest谷歌翻譯Api錯誤414(Request-URI太大)java
但是,當我嘗試翻譯超過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上的代理。
謝謝你的答覆,但我怕我不明白你 - 我做了POST,把參數請求主體。就像這裏:http://www.javadb.com/sending-a-post-request-with-parameters-from-a-java-class – user1049280
我已更新問題。 – user1049280