Google Cloud Vision API - 如何启用服务帐户

sma*_*zie 5 java google-cloud-platform google-cloud-vision

我试图了解GoogleVision API Java库.

我创建了一个服务帐户,下载了json并设置了这个环境变量.

GOOGLE_APPLICATION_CREDENTIALS=C:\GoogleAPI\keys\translate-41428d4d1ec6.json
Run Code Online (Sandbox Code Playgroud)

我使用以下方法设置了应用程序默认凭据:

gcloud beta auth application-default login
Run Code Online (Sandbox Code Playgroud)

我在这里关注这个例子:https: //cloud.google.com/vision/docs/reference/libraries

我现在假设所有调用都将使用服务帐户,就像魔术一样,因为我没有在代码中进行任何身份验证(根据示例).

但是,我无法看到我授权服务帐户使用Google Vision API的位置,我认为我必须这样做.所以,我可能根本就不能使用服务帐户......

当我进入IAM并尝试为服务帐户分配"角色"时,与视觉API没有任何关系?有角色,如

  • 我怎样才能确定我使用服务帐户拨打电话?
  • 如果未在IAM中列出特定API(例如GoogleVision),我还需要明确允许服务帐户访问特定API ...或者与项目相关的所有服务帐户是否都可以访问API?

文档中的示例显示了如何

任何帮助赞赏.

此外,我感兴趣的是如何调整示例以不使用Application Default Credentials,但实际上创建了一个特定的Credential实例并使用它来调用Google Vision,因为这一点并不清楚.示例给出的是调用GoogleStorage,但我无法将其转换为Google Vision.

public class StorageFactory {
  private static Storage instance = null;

  public static synchronized Storage getService() throws IOException, GeneralSecurityException {
    if (instance == null) {
      instance = buildService();
    }
    return instance;
  }

  private static Storage buildService() throws IOException, GeneralSecurityException {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // Depending on the environment that provides the default credentials (for
    // example: Compute Engine, App Engine), the credentials may require us to
    // specify the scopes we need explicitly.  Check for this case, and inject
    // the Cloud Storage scope if required.
    if (credential.createScopedRequired()) {
      Collection<String> scopes = StorageScopes.all();
      credential = credential.createScoped(scopes);
    }

    return new Storage.Builder(transport, jsonFactory, credential)
        .setApplicationName("GCS Samples")
        .build();
  }
}
Run Code Online (Sandbox Code Playgroud)

并且不要让我开始2小时我只是浪费了"拒绝访问"...这显然是由于图像大小超过4mb,与凭证无关!

小智 5

您无需授权服务​​帐户即可访问vision API.在项目中启用API并使用与该项目关联的服务帐户就足够了.如果你还有问题,请告诉我.