将Google Cloud Vision API与简单的API密钥配合使用

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

我正在使用此处记录的Google Cloud Vision Java API客户端:https://cloud.google.com/vision/docs/reference/libraries

如果我通过将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为引用右侧“服务帐户”的json文件来使用隐式默认凭据,则以下快速入门代码可以正常工作。

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

    ...
  }
}

但是,我想使用简单的(单字符串)API密钥而不是服务帐户对API进行身份验证,我找不到解释如何通过此Java库执行此操作的文档。可能吗?

java google-api api-key google-cloud-vision
1个回答
1
投票

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

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

替换你的线

ImageAnnotatorClient vision = ImageAnnotatorClient.create();

ImageAnnotatorClient vision = ImageAnnotatorClient.create(ias);

试试看!

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