使用 Google Translate V3 API 验证服务帐户的默认方式是通过环境变量。此环境变量称为 GOOGLE_APPLICATION_CREDENTIALS,指向带有凭据的 json 文件,如下所述: https://cloud.google.com/docs/authentication/production
但是,在不同位置使用文件时如何使用所需的凭据?我可以从 FileStream 创建凭证对象,如谷歌文档中所述。但是,使用此凭据对象仅记录了谷歌云存储。 TranslateTextRequest 的构建器不接受此类凭据对象。 https://googleapis.dev/dotnet/Google.Cloud.Translate.V3/2.0.0/api/Google.Cloud.Translate.V3.TranslateTextRequest.html
唯一的解决方法是将文件复制到环境变量中指定的位置,但这看起来很奇怪,并且在未设置该变量时会失败。
最佳答案
所以,我终于能够解决这个问题了。
@JohnHanley 不幸的是,类(class) TranslationServiceClientBuilder
在我的环境中不可用。也许它是 DotNet 特定的。然而,这个提示仍然非常有帮助,因为我发现另一个构建器创建了 TranslationServiceSettings
的实例。 ,它又具有一个静态工厂方法,该方法又可用于实例化 TranslationServiceClient
.
以下是如何从 Google JSON 凭据文件的文件路径创建 TranslationServiceClient 的完整解决方案。
TranslationServiceSettings settings = TranslationServiceSettings.newBuilder().setCredentialsProvider(new CredentialsProvider() {
@Override
public Credentials getCredentials() throws IOException {
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsFileAbsPath))
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
return credentials;
}
}).build();
TranslationServiceClient translationServiceClient = TranslationServiceClient.create(settings);
当然,匿名类也可以替换为 Lambda 表达式。
@PjotrS 很抱歉造成困惑。我指的文件是 JSON 凭证文件,而不是要翻译的文件。
关于authentication - 谷歌翻译API V3 : How to authenticate service account from file stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68436263/