缺少有关 Google Translation API 客户端问题的有效 API 密钥?

Fed*_*rer 5 java google-api google-translate google-api-java-client google-translator-toolkit

我按照https://cloud.google.com/translate/docs/reference/libraries#client-libraries-usage-java开始 java 客户端演示。我已经将set json文件身份验证到环境变量GOOGLE_APPLICATION_CREDENTIALS。但是,当我运行 java 示例代码时,我得到了 translateException。

Exception in thread "main" com.google.cloud.translate.TranslateException: The request is missing a valid API key.
at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:61)
at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:144)
at com.google.cloud.translate.TranslateImpl$4.call(TranslateImpl.java:113)
at com.google.cloud.translate.TranslateImpl$4.call(TranslateImpl.java:110)
Caused by: 
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 
Forbidden
{
  "code" : 403,
  "errors" : [ {
  "domain" : "global",
  "message" : "The request is missing a valid API key.",
  "reason" : "forbidden"
} ],
  "message" : "The request is missing a valid API key.",
  "status" : "PERMISSION_DENIED"
}
Run Code Online (Sandbox Code Playgroud)

该文档显示此 JSON 文件包含关键信息。

示例代码如下所示

    // Instantiates a client
    Translate translate = TranslateOptions.getDefaultInstance().getService();
    // The text to translate
    String text = "Hello, world!";
    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));
    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.getTranslatedText());
Run Code Online (Sandbox Code Playgroud)

我不知道如何设置 api-key。在我为keyand设置环境变量后它仍然不起作用credentials

在此处输入图片说明

Yus*_*han 6

您可以尝试通过您的服务帐户 json 文件进行身份验证,如下所示

它在节点中非常简单

 // Instantiates a client
 const translate = new Translate(
        {
                projectId: 'your project id', //eg my-project-0o0o0o0o'
                keyFilename: 'path of your service acount json file' //eg my-project-0fwewexyz.json
        }
    ); 
Run Code Online (Sandbox Code Playgroud)

您可以参考https://cloud.google.com/bigquery/docs/authentication/service-account-file for java


DaI*_*mTo 4

要向 Google Translation 发出经过身份验证的请求,您必须使用凭据创建服务对象或使用 API 密钥。最简单的身份验证方法是使用应用程序默认凭据。这些凭据是从您的环境中自动推断的,因此您只需要以下代码来创建服务对象:

Translate translate = TranslateOptions.getDefaultInstance().getService();
Run Code Online (Sandbox Code Playgroud)

我个人从来没有让它发挥作用。

此代码也可以与 API 密钥一起使用。默认情况下,会在环境变量中查找 API 密钥GOOGLE_API_KEY。设置 API 密钥后,您可以通过调用通过创建的翻译服务上的方法来进行 API 调用TranslateOptions.getDefaultInstance().getService()

示例项目在这里