Xia*_* Er 6 android google-translate google-cloud-iam google-translation-api
我正在尝试在我的应用程序中使用 Google Cloud Translation API,但每当我尝试翻译某些内容时,都会出现缺少有效 API 的错误。
我已经完成了快速启动步骤,但没有成功。
我已经尝试了客户端库身份验证中的步骤,但也不起作用。
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)
.. 18 more
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)
... 4 more
at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate(HttpTranslateRpc.java:130)
... 19 more
Run Code Online (Sandbox Code Playgroud)
如果您正在使用客户端库并且已经下载了服务帐户 json 文件,请尝试执行以下操作:
// Instantiates a client
const translate = new Translate({
projectId: 'your project id', //eg my-proj-0o0o0o0o'
keyFilename: 'path of your service acount json file' //eg my-proj-0fwewexyz.json
});
Run Code Online (Sandbox Code Playgroud)
而不是这个:
// Instantiates a client
const translate = new Translate({projectId});
Run Code Online (Sandbox Code Playgroud)
这样您只需要服务帐户 json 文件并启用特定的 API
小智 2
API 密钥错误意味着您没有正确创建或使用该密钥。您需要执行以下操作才能使密钥正常工作:
GOOGLE_APPLICATION_CREDENTIALS为密钥的文件路径,请参考快速入门教程中的示例我建议在 GCP Console 中执行 #1 和 #2,并在 Cloud Shell 中处理 #3 和 #4。