Google API转换返回错误

时间:2012-08-25 10:37:17

标签: java google-api

我有一部分代码使用谷歌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

1 个答案:

答案 0 :(得分:1)

您必须在APIs Console

中的项目的“服务”标签中启用翻译API

此页面包含所有定价详情:https://developers.google.com/translate/v2/pricing