Google Cloud Translate - 403 Forbidden Missing API密钥

时间:2018-03-27 09:39:08

标签: java unix google-api google-cloud-platform google-translate

我已经通过Google云转换API并决定将Java平台用于我的应用程序

根据文档,使用所需的jar测试下面的代码。这段代码在我的日食中工作正常

export

然而,当将此代码导出到jar并在Shell脚本/ Unix服务器中运行时,我得到以下错误说明,权限定义 - 请求缺少有效的API密钥。 如何以及在哪里可以使用Java代码中的API密钥,我有一个授权的服务帐户。

我已尝试使用我的服务帐户进行Google transalte工作正常,以下是示例。但是,我不确定如何在JAVA代码中使用此密钥

CURL命令 - 正常工作

        Translate translate = TranslateOptions.getDefaultInstance().getService();

        String name = rs.getString("name");
        Translation translation1 = translate.translate(name);
        String TransalateName = translation1.getTranslatedText();

错误:

curl -X POST \
     -H "Authorization: Bearer "AUTH_TOKEN_HERE \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': '你好',
  'target': 'en',
  'model': 'nmt',
}" "https://translation.googleapis.com/language/translate/v2"

1 个答案:

答案 0 :(得分:0)

您错过了对GoogleAPI.setKey的调用。

import com.google.api.GoogleAPI;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

GoogleAPI.setKey(API_KEY);
GoogleAPI.setHttpReferrer("https://...");
// normally you would catch errors
Translate.DEFAULT.execute(sourceText, Language.fromString(sourceLanguageCode),
            Language.fromString(targetLanguageCode));

参见例如https://www.programcreek.com/java-api-examples/?api=com.google.api.GoogleAPI。我必须说,谷歌云文档中没有例子(我能找到)是令人失望的。