简体   繁体   中英

Using the Google Cloud Vision API with a simple API key

I am using the Google Cloud Vision Java API client documented here: https://cloud.google.com/vision/docs/reference/libraries .

The following quickstart code works fine if I use the implicit default credentials by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to reference a json file for the right "service account".

// Imports the Google Cloud client library
import com.google.cloud.vision.spi.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;

...


public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    ImageAnnotatorClient vision = ImageAnnotatorClient.create();

    ...

    BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
    List<AnnotateImageResponse> responses = response.getResponsesList();

    ...
  }
}

However, I want to authenticate to the API using a simple (single-string) API key rather than a service account, and I cannot find documentation explaining how to do that through this java library. Is it possible?

It's possible: Create an ImageAnnotatorSettings like:

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

replace your line

ImageAnnotatorClient vision = ImageAnnotatorClient.create();

with

ImageAnnotatorClient vision = ImageAnnotatorClient.create(ias);

Give it a try!

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