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

mac*_*021 7 java google-api api-key google-cloud-vision

我正在使用此处记录的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();

    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 0

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

ImageAnnotatorSettings ias = ImageAnnotatorSettings.newBuilder()
        .setCredentialsProvider(
                FixedCredentialsProvider.create(#InputStream of your json key#)
        )
        .build();
Run Code Online (Sandbox Code Playgroud)

更换你的线路

ImageAnnotatorClient vision = ImageAnnotatorClient.create();
Run Code Online (Sandbox Code Playgroud)

ImageAnnotatorClient vision = ImageAnnotatorClient.create(ias);
Run Code Online (Sandbox Code Playgroud)

试一试!