Google Vision API java客户端:如何在代码中显式设置API凭据(不使用环境变量)

问题描述 投票:0回答:1

我正在尝试将我的项目与Google Vision API集成

以下是您检查我尝试集成的客户端版本的maven依赖项:

<dependency>
   <groupId>com.google.cloud</groupId>
   <artifactId>google-cloud-vision</artifactId>
   <version>1.51.0</version>
</dependency>

文档提供的设置API身份验证凭据的方式如下:

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the 
file path of the JSON file that contains your service account key

我想知道是否有一种方法可以在代码中显式设置凭证,因为这比在我们运行项目的每个环境中设置环境变量更方便。

据我所知,以前的客户端版本1.22可能会执行以下操作:

def credentialFile = this.class.classLoader
.getResource(grailsApplication.config.credentialsFile)
GoogleCredential credential = 
GoogleCredential.fromStream(credentialFile.openStream())
        .createScoped(grailsApplication.config.googleScope)

Vision vision = new 
Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), 
jsonFactory, credential).build()

但对于新的客户端API,我无法找到方法,文档在这方面没有说什么。

java credentials google-vision explicit client-library
1个回答
1
投票

有可能:创建一个ImageAnnotatorSettings,如:

ImageAnnotatorSettings ias = ImageAnnotatorSettings.newBuilder()
            .setCredentialsProvider(
                    FixedCredentialsProvider.create(#InputStream of your json key#)
            )
            .build();

将此添加到您的客户端并发消息!

© www.soinside.com 2019 - 2024. All rights reserved.