我有一部分代码使用谷歌api翻译,我写的代码像这样
package pp;
import com.google.api.GoogleAPI;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class tr
{
public static void main(String[] args) throws Exception{
GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
GoogleAPI.setKey("AIzaSyBi7y4EgC0B-Q9UZg-tOzsOI0sLQ8F1Oow");
String result = Translate.DEFAULT.execute("hello", Language.ENGLISH, Language.ARABIC);
System.out.println(result);
System.out.println("succeeded");
}
}
但当我运行它时,我得到了这个错误
调试结果:错误:[google api translate java]检索翻译时出错。
运行结果
Error: [google-api-translate-java] Error retrieving translation.
Exception in thread "main" com.google.api.GoogleAPIException: java.lang.Exception: [google-api-translate-java] Error retrieving translation.
at com.google.api.translate.TranslateV2.execute(TranslateV2.java:68)
at pp.tr.main(tr.java:14)
Caused by: java.lang.Exception: [google-api-translate-java] Error retrieving translation.
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:99)
at com.google.api.translate.TranslateV2.execute(TranslateV2.java:62)
... 1 more
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.googleapis.com/language/translate/v2?key=AIzaSyBi7y4EgC0B-Q9UZg-tOzsOI0sLQ8F1Oow&q=hello&target=ar&source=en
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1458)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1452)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1106)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:93)
... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.googleapis.com/language/translate/v2?key=AIzaSyBi7y4EgC0B-Q9UZg-tOzsOI0sLQ8F1Oow&q=hello&target=ar&source=en
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:89)
... 2 more
您必须在API控制台中从项目的"服务"选项卡启用翻译API。
此页面包含所有定价详细信息:https://developers.google.com/translate/v2/pricing