简体   繁体   中英

Google Vision API java client: how to set API credentials explicitly in code(without using environment variable)

I'm trying to integrate my project with Google Vision API

Here is the maven dependency for you to check the client version I'm trying to integrate with:

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

The way the documentation offers to set the API authentication credentials is the following:

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

I'm wondering if there is a way to set the credentials explicitly in code as that is more convenient than setting environment variables in each and every environment we are running our project on.

As I know for a former client version 1.22 that was possible doing the following:

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()

But for the new client API I was not able to find the way and documentation doesn't say anything in that regards.

It's possible: Create an ImageAnnotatorSettings like:

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

Add this to your client and voilá!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM