com.google.api.client.googleapis.auth.oauth2.Google凭据现在已弃用

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

Google的视觉API的sample code显示了此内容:

  public static Vision getVisionService() throws IOException, GeneralSecurityException {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
  }

但是com.google.api.client.googleapis.auth.oauth2.GoogleCredential现在已弃用。现在验证上面内容的正确方法是什么?

java google-app-engine google-cloud-platform google-vision
1个回答
0
投票

您可以通过几种方法执行此操作。

选项1:

  1. 按照此quickstart page上的步骤
  2. 设置GOOGLE_APPLICATION_CREDENTIALS,这是客户端库默认使用的内容

选项2:

  1. 您自己加载服务密钥文件。
// imports
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;

import java.io.FileInputStream;

// somewhere in your code, load the credentials
try {
  Credentials credentials = GoogleCredentials.fromStream(
        new FileInputStream("path_to_file.json"));

  FixedCredentialsProvider fixedCredentialsProvider =
        FixedCredentialsProvider.create(credentials);

  ImageAnnotatorSettings settings = 
        ImageAnnotatorSettings.newBuilder()
           .setCredentialsProvider(
               fixedCredentialsProvider).build();

  ImageAnnotatorClient client = 
        ImageAnnotatorClient.create(settings);
catch(IOException e) {
  e.printStackTrace(e);
}

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