Google vision API从文件加载凭据

时间:2018-02-18 10:08:11

标签: java credentials google-cloud-vision

我想在创建Annotator客户端时使用不同的凭证文件。我现在能够使用transalte API这样做:

 Credentials creds = ServiceAccountCredentials.fromStream(new FileInputStream("path/to/credentials.json"));
 return TranslateOptions.newBuilder().setCredentials(creds).build().getService();  

是否有与ImageAnnotatorClient

相同的方法

编辑:我正在使用google cloud java sdk版本:1.16.0

2 个答案:

答案 0 :(得分:3)

ServiceAccountCredentials - > FixedCredentialsProvider - > ImageAnnotatorSettings.Builder - > ImageAnnotatorSettings - > ImageAnnotatorClient

示例(从文档中复制):

Credentials myCredentials = ServiceAccountCredentials.fromStream(
    new FileInputStream("path/to/credentials.json"));

ImageAnnotatorSettings imageAnnotatorSettings =
    ImageAnnotatorSettings.newBuilder()
    .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
    .build();

ImageAnnotatorClient imageAnnotatorClient =
    ImageAnnotatorClient.create(imageAnnotatorSettings);

这方面的文档(仍然)令人惊讶地发现和导航令人沮丧。他们之间并不是一贯的联系,有多个版本浮动,网址的变化频率超过应有的水平,而Google的一些链接会返回404.

  • ImageAnnotatorClient:com.google.cloud.vision.v1.ImageAnnotatorClient
  • ImageAnnotatorSettings:com.google.cloud.vision.v1.ImageAnnotatorSettings
  • ClientSettings.Builder:com.google.api.gax.rpc.ClientSettings.Builder
  • FixedCredentialsProvider:com.google.api.gax.core.FixedCredentialsProvider
  • ServiceAccountCredentials:com.google.auth.oauth2.ServiceAccountCredentials

答案 1 :(得分:0)

private static ImageAnnotatorSettings  setImageAnnotator() {
    Credentials myCredentials = null;
    try {
        myCredentials = ServiceAccountCredentials.fromStream(
                new FileInputStream("C:\\Users\\Pictures\\Cloudvision\\credentials.json"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        ImageAnnotatorSettings imageAnnotatorSettings = null;
        try {
            imageAnnotatorSettings = ImageAnnotatorSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
            .build();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }