我遵循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"
}文档显示这个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());我不知道如何设置api键。在我为key和credentials设置了环境变量之后,它仍然无法工作。

发布于 2018-03-20 10:17:57
要向Google翻译发出经过身份验证的请求,必须创建具有凭据的服务对象或使用API密钥。最简单的身份验证方法是使用应用程序默认凭据。这些凭据是从您的环境中自动推断出来的,因此您只需要使用以下代码来创建服务对象:
Translate translate = TranslateOptions.getDefaultInstance().getService();我个人从来没有让它起作用。
此代码还可以与API密钥一起使用。默认情况下,在GOOGLE_API_KEY环境变量中查找API键。一旦设置了API键,就可以通过调用通过TranslateOptions.getDefaultInstance().getService()创建的翻译服务上的方法来调用API。
样例项目这里
发布于 2019-07-06 10:00:57
您可以尝试通过您的服务来验证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
}
); 您可以使用java的参考https://cloud.google.com/bigquery/docs/authentication/service-account-file。
发布于 2018-04-02 16:05:48
通过在命令提示符上运行"gcloud auth应用程序-默认登录“,我能够让google翻译工作。这在要求您使用google帐户授权后,将凭据重新生成到默认位置。有关更多详细信息,请参阅https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-translate。
https://stackoverflow.com/questions/49379897
复制相似问题