Google Cloud Translation API请求缺少有效的API密钥

时间:2018-05-28 13:32:37

标签: android google-translate google-translation-api google-cloud-iam

我正在尝试在我的应用程序中使用Google Cloud Translation API,但每当我尝试翻译某些内容时,都会遇到此错误的有效API错误。

我已经完成了快速启动步骤,但没有奏效。 https://cloud.google.com/translate/docs/quickstart

我已经尝试过客户端库身份验证中的步骤,但是没有用。 https://cloud.google.com/translate/docs/reference/libraries

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: herrsa1.bit.translator, PID: 16598
              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)
                  at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:89)
                  at com.google.cloud.RetryHelper.run(RetryHelper.java:74)
                  at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:51)
                  at com.google.cloud.translate.TranslateImpl.translate(TranslateImpl.java:110)
                  at com.google.cloud.translate.TranslateImpl.translate(TranslateImpl.java:124)
                  at herrsa1.bit.translator.MainActivity.translateText(MainActivity.java:61)
                  at herrsa1.bit.translator.MainActivity$1.onClick(MainActivity.java:48)
                  at android.view.View.performClick(View.java:6261)
                  at android.widget.TextView.performClick(TextView.java:11180)
                  at android.view.View$PerformClick.run(View.java:23748)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6776)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
               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"
              }
                  at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
                  at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
                  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
                  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
                  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
                  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
                  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
                  at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:130)
                    ... 19 more

3 个答案:

答案 0 :(得分:0)

API密钥错误表示您未正确创建或使用密钥。您需要执行以下操作才能使密钥起作用:
1)创建一个服务帐户[1]
2)为上述服务帐户[2]创建密钥。
3)将密钥下载到某个位置,例如本地路径
4)将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为密钥的文件路径,请参阅快速入门教程中的示例

在GCP控制台中执行1)和2),在Cloud Shell中执行3)和4)是最简单的。

[1] https://cloud.google.com/iam/docs/creating-managing-service-accounts#creating_a_service_account
[2] https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating_service_account_keys

答案 1 :(得分:0)

如果您正在使用客户端库,并且已经下载了服务帐户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
        }
    ); 

代替

  // Instantiates a client
  const translate = new Translate({projectId});

这样,您只需要服务帐户json文件和启用的特定API

答案 2 :(得分:-1)

我也尝试执行this示例程序。 我遵循了same的说明。但是当我执行时,我遇到了同样的错误(请求缺少有效的API密钥)。

我在示例程序中更改了一行。

代替

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

我添加了

Translate translate = TranslateOptions
            .newBuilder()
            .setCredentials(
                ServiceAccountCredentials
                            .fromStream(new FileInputStream(
                                    "YourCredentialFilePath.json")))
            .build().getService();

现在可以使用了。

修复后的示例代码。

// Imports the Google Cloud client library
import java.io.FileInputStream;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
   public static void main(String... args) throws Exception {
      //Instantiates a client
      //Removed next line
      //Translate translate = TranslateOptions.getDefaultInstance().getService();
      //Added this line
      Translate translate = TranslateOptions
            .newBuilder()
            .setCredentials(
            ServiceAccountCredentials
                            .fromStream(new FileInputStream(
                                    "YourCredentialFilePath.json")))
            .build().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());
   }
}